2016-02-18 21 views
0

兩個上下文中的this的值是什麼以及一個嵌套函數如何引用另一個函數的返回值?在JavaScript中,如何從更深的嵌套方法引用方法的返回值

var rootObj = { 
    nestedObjA: { 
     functionA: function() { 
      // what is value of 'this' here? 
      return 'foo'; 
     } 
    }, 
    nestedObjB: { 
     functionB: function() { 
      // how to reference? >> rootObj.nestedObjA.functionA 
      // what is the value of 'this' here? 
     } 
    } 
} 
+0

你是不是指'''而不是'='?這是一個語法錯誤。 – Bergi

+1

你不能試試嗎? '的console.log(本);'。 – Bergi

+0

我會修復這個錯字。我想知道'this'作爲答案的一部分,僅僅爲了將來的讀者和完整性。 – Ben

回答

0

兩種功能中的的this值應爲rootObj.nestedObjA.functionArootObj.nestedObjB.functionB,分別。要檢查this的值,可以在每個函數中添加console.dir(this)

要從函數返回值,您應該在函數體中添加return,例如; return rootObj.nestedObjA.functionA()rootObj.nestedObjB.functionB

var rootObj = { 
 
    nestedObjA: { 
 
     functionA: function() { 
 
      // what is value of 'this' here? 
 
      console.dir(this); 
 
      return 'foo'; 
 
     } 
 
    }, 
 
    nestedObjB: { 
 
     functionB: function() { 
 
      // how to reference? >> rootObj.nestedObjA.functionA 
 
      // what is the value of 'this' here? 
 
      console.dir(this); 
 
      return rootObj.nestedObjA.functionA() 
 
     } 
 
    } 
 
} 
 

 
var res = rootObj.nestedObjB.functionB(); 
 
console.log(res); // 'foo'

1

沒有保證的回答「的this在函數中的價值是什麼?」,你可以用函數的apply()/call()方法設置原型。

var rootObj = { 
    nestedObjA: { 
    functionA: function() { 
     var foo = "bar"; 
     return foo; 
    } 
    }, 
    nestedObjB: { 
    functionB: function() { 
     var foo = this.nestedObjA.functionA(); 
     console.log(foo); 
    } 
    } 
} 

// When calling functionB() you could use: 
rootObj.nestedObjB.functionB.apply(rootObj); 

默認的this值是functionB功能範圍;