Javascript 变量不包含对“this”的引用`
Javascript 变量不包含对“this”的引用`,javascript,Javascript,函数test1(){ this.name='test1'; var=这个; 函数test2(){ this.name='test2'; console.log(that.name); } test2(); } test1()您的变量,将成为对象引用,因为您将关键字this指定给它。这意味着变量,将是一个对象,它将引用这个(即当前对象) 此外,的变量不是值类型。它是一个物体 有关这方面的更多信息,请搜索“值类型与引用类型” 希望这有帮助。在函数定义中,这指的是函数的“所有者”。 请在内联注释中找到
函数test1(){
this.name='test1';
var=这个;
函数test2(){
this.name='test2';
console.log(that.name);
}
test2();
}
test1()编码>您的变量,将成为对象引用,因为您将关键字this指定给它。这意味着变量,将是一个对象,它将引用这个(即当前对象)
此外,的变量不是值类型。它是一个物体
有关这方面的更多信息,请搜索“值类型与引用类型”
希望这有帮助。在函数定义中,这指的是函数的“所有者”。
请在内联注释中找到描述。
根据执行顺序重新排列代码
test1(); //Now this is called by window object
function test1() {
this.name = 'test1'; //window.name = 'test1';
var that = this; //that is also now window obj
test2(); //this.test2 or window.test2()
function test2() {
this.name = 'test2'; //window.name is now test 2
console.log(that.name); //since in third step, that is window, that.name or window.name is now test 2
}
}
因为那个
和这两个都指向全局对象窗口
。您没有创建一个实例(使用new
)以便this
(属于test1
)将是该实例,您只是直接调用函数。请尝试:var a=new test1()代码>或只是新建test1()代码>(简称)。如果您记录了这些变量,这将有助于您理解。可能存在“该变量的重复项以保存对test1函数的引用”。这不是JavaScript中的“this”或“that”。它们不包含对函数的引用,而是包含对象引用。