【发布时间】:2017-09-18 07:43:26
【问题描述】:
我正在阅读 JS Definitive Guide 6th edition,我遇到了以下几行:
与变量不同,this 关键字没有作用域,嵌套函数没有 继承调用者的 this 值。如果嵌套函数作为方法调用,它的 这个值是它被调用的对象。如果嵌套函数作为函数调用 那么它的 this 值将是全局对象(非严格模式)或未定义(严格 模式)。
我的理解是函数在严格模式下返回全局或未定义作为 this 的值。同样在 methods 中, this 指的是调用该方法的对象。 从函数或方法调用的嵌套函数也有 this 引用全局或严格模式下未定义的对象。
举个例子:
var o = { // An object o.
m: function() { // Method m of the object.
var self = this; // Save the this value in a variable.
console.log(this === o); // Prints "true": this is the object o.
f(); // Now call the helper function f().
function f() { // A nested function f
console.log(this === o); // "false": this is global or undefined
console.log(self === o); // "true": self is the outer this value.
}
}
};
o.m(); // Invoke the method m on the object o.
但我不明白的是:如果将嵌套函数作为方法调用,它的 this 值就是它被调用的对象。
你能举个例子,嵌套函数作为方法被调用并且它的 this 值引用了它被调用的对象吗?
【问题讨论】:
-
只需执行
o.method = f;即可调用它为o.method()
标签: javascript function methods nested this