2017-04-21 130 views
1

我在看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. 

但我不明白的是:如果一个嵌套函数被调用的方法,其这个值是它是在调用的对象。

你能给我一个嵌套函数作为方法调用的例子,它的这个值引用了它被调用的对象吗?

+0

只是做'o.method = F;',你可以调用它作为'o.method()' – Bergi

回答

0

如果我正确理解,

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. 
     } 
在上面的代码

thiswindow对象。如果你想this指向o对象本身,那么你应该可以使用apply, bind, or call

像这样f.call(this)

+0

很好的解决方法,以取代像代码 '变种是=这个' – pollx

0

例如,如果m方法将返回具有n方法,你可以看到的this在方法这方面的另一个目的是,嵌套的对象,而不是父对象为this.a是不确定的。

var o = { 
 
    a: 1, 
 
    m: function() { 
 
    console.log('Parent: ' + this.a) 
 
    
 
    return { 
 
    \t b: 2, 
 
    \t n: function() { 
 
     \t console.log('Nested: ' + this.a); 
 
     console.log('Nested: ' + this.b); 
 
     } 
 
    } 
 
    } 
 
}; 
 

 
o.m().n()