Har*_*per 2 javascript object-literal javascript-objects
我有一个像这样的对象文字:
var test = {
one: function() {
},
two: function() {
this.one(); // call 1
test.one(); // call 2
}
};
Run Code Online (Sandbox Code Playgroud)
two函数中的调用之间有什么区别(使用对象文字名称和使用对象this)?
test始终在two函数闭包内绑定到变量,test而this取决于函数的调用方式.如果使用常规对象成员访问语法调用该函数,则this成为拥有该函数的对象:
test.two(); // inside, "this" refers to the object "test"
Run Code Online (Sandbox Code Playgroud)
您可以this使用Function.prototype.call以下命令更改值:
test.two.call(bar); // inside, "this" refers to the object "bar"
Run Code Online (Sandbox Code Playgroud)
但无论函数如何被调用,函数test内部的值都保持不变two.