this 总是1评估为调用函数对象的对象。它将评估window它是否“在任何情况下调用”(或者是 的属性window)。
(请注意,这this 不是变量,因此不会在闭包中封闭!这就是为什么有时需要闭包来获得变量or orthis经常知道的“正确” 。)selfthat_this
例如:
function f () { return this; }
var a = {f: f}
var b = {f: f}
a.f() === a // true
b.f() === b // true
f() === window // true
使用变量创建与当前的绑定的示例(截至调用封闭函数时)this:
test = (function() {
var self = this // <-- variable, which is "closed over"
this.value = 1; // self === this
this.print = function() {
console.log(self.value); // <-- self "names" previous this object
};
return this;
})();
1这是一个小谎言。Function.callandFunction.apply函数允许指定上下文,this并且可以由“上下文绑定”函数使用,例如Function.bind消除对显式“自闭包”的需要,如上所示。