阅读 Doug 的“Javascript: the goods parts”中关于函数的第 4 章谈论“方法调用模式”和“函数调用模式”(第 28 页)。
When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object.
这很清楚。然后在同一页面:
When a function is not the property of an object, then it is invoked as a function:
var sum = add(3, 4); // sum is 7
When a function is invoked with this pattern, this is bound to the global object. This was a mistake in the design of the language.
我的问题:
- 1.- “this is bound to the global object”意味着this被绑定(bind)到全局范围?
- 2.- “这是语言设计中的一个错误”意味着this 应该遵循与方法遵循的相同规则?即,将this 绑定(bind)到他自己?
谢谢。-
编辑:给出的两个答案都非常有指导意义并且有据可查。感谢所有参与者。
最佳答案
1 - 是
2 - 如果您继续阅读,紧接着他描述了一个示例,使其成为“语言设计中的错误”。
var myObject = {
value: 1
};
myObject.double = function() {
var that = this;
var helper = function() {
alert('in helper, this.value = ' + this.value + ' and that.value = ' + that.value);
that.value = that.value + that.value;
}
helper();
};
myObject.double();
alert('after doubling, myObject.value = ' + myObject.value);
警报将显示在作为对象属性的函数中使用“this”将不起作用。如果全局对象(可能是窗口)有一个 .value
,那么会在该警报中看到它。
关于javascript - 对此,全局对象和全局范围的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173539/