window.name = "window";
object = {
name: "object",
method: function () {
var self = this;
var nestedMethod = function () {
console.log(self.name); // or object.name without declaring self
}
nestedMethod();
}
}
object.method(); // print 'object'
保存对象的范围 - 或使用对象本身!
我们创建的所有匿名函数都会在全局范围内运行吗?
不,不是所有的匿名函数都失去了它们的作用域,所有的函数作用域都绑定到全局对象(如果它们不是用 specific 调用的this
,请参见apply
and call
,请参见下面的示例)!
window.name = "window";
object = {
name: "object",
method: function () {
var nestedMethod = function () {
console.log(this.name);
}
nestedMethod.call(this); //change the this arg in the current object scope
// when you call this function with .call(this) you are changing the value of the nestedMethod's this to the current this, which is object
}
}
object.method(); // print 'object'