我在看JS权威指南第6版援引为方法,我在这些线路传来:嵌套函数在JavaScript
与变量不同,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.
但我不明白的是:如果一个嵌套函数被调用的方法,其这个值是它是在调用的对象。
你能给我一个嵌套函数作为方法调用的例子,它的这个值引用了它被调用的对象吗?
只是做'o.method = F;',你可以调用它作为'o.method()' – Bergi