我正在尝试创建一个没有原型(prototype)的类。这是一个例子:
test = (function() {
this.value = 1;
this.print = function() {
console.log(this.value);
};
return this;
})();
这完全符合预期。我不明白的是 this.print
函数中的 this.value
。 this.print
如何正确地知道任何提到的 this
都是指 test
而不是 window
?通过 this.___ = function(){}
定义的任何函数都会自动将 this
添加为上下文吗?
最佳答案
this
always1 计算调用函数对象的对象。如果它是“无条件调用”(或者是 window
的属性),它将计算为 window
。
(请注意,this
不是变量,因此不是闭包中的闭包!这就是为什么有时需要闭包获取“正确的”this
,通常由变量 self
或 that
或 _this
知道。)
例如:
function f () { return this; }
var a = {f: f}
var b = {f: f}
a.f() === a // true
b.f() === b // true
f() === window // true
使用变量创建绑定(bind)到当前(调用封闭函数时)的示例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.call
和 Function.apply
函数允许指定 this
上下文并且可以被“上下文绑定(bind)”函数使用,例如 Function.bind
消除如上所示的显式“ self 关闭”的需要。
关于javascript - `this` 在不是类原型(prototype)的函数内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10965485/