gpt4 book ai didi

javascript - 变量不持有对 `this` 的引用

转载 作者:行者123 更新时间:2023-11-29 15:14:34 25 4
gpt4 key购买 nike

function test1() {
this.name = 'test1';
var that = this;

function test2() {
this.name = 'test2';
console.log(that.name);
}

test2();
}

test1();

执行时,我希望控制台注销 test1。为什么我得到的是 test2?我希望 that 变量包含对 test1 函数的引用。

最佳答案

你的变量 that 成为一个对象引用,因为你为它分配了关键字 this 。这意味着变量 that 将是一个对象,并且它将引用 this(即当前对象)。

此外,变量that 不是值类型。它是一个对象。

有关这方面的更多信息,请搜索“值类型与引用类型”。

希望这对您有所帮助。

关于javascript - 变量不持有对 `this` 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com