[英]JS Calling functions from a nested object inside this object
實際上我試圖運行以下代碼:
var myObj = { subObj: { methodA: (parA) => { this.methodB(parA); //This is not working }, methodB: (parB) => { console.log(parB); } } } myObj.subObj.methodA('Hello World');
為什么我會收到此錯誤? 方法A的scope中的“methodB”不是通過'this'嗎?
非常感謝
箭頭函數具有特殊綁定。 箭頭函數中this
的值等同於定義 function 的 this 的值(詞法范圍)。 在這種情況下窗口(在瀏覽器中)。 要使您的 function 工作, this
使用引用封閉上下文的常規函數:
var myObj = {
subObj: {
methodA: function (parA) {
this.methodB(parA); //This is not working
},
methodB: function (parB) {
console.log(parB);
}
}
}
myObj.subObj.methodA('Hello World');
更多關於此的解釋here 。
箭頭函數沒有單獨的this 。
因此做
var myObj = {
subObj: {
methodA: (parA) => {
this.methodB(parA); // `this` will always be window / outer context as arrow functions will not bind `this` at runtime.
},
methodB: (parB) => {
console.log(parB);
}
}
}
myObj.subObj.methodA('Hello World'); // fails as `this.methodB` in your `methodA` is equivalent to `window.methodB` which is not present
類似於做:
var myObj = {
subObj: {
methodA: function(parA) {
this.methodB(parA);
},
methodB: function(parB) {
console.log(parB);
}
}
}
myObj.subObj.methodA.call(window || {}, 'Hello World'); // where window || {} is the lexical / outer scope to your function.
在后者的情況下,當您執行以下操作時,事情會起作用:
myObj.subObj.methodA('Hello World');
由於普通函數使用調用者的
this
並且您將methodA
稱為myObj.subObj.methodA
,this
=myObj.subObj
。 因此this.methodB
可用,因為它等同於myObj.subObj.methodB
我的猜測是,這是因為所有這些都是匿名的、非范圍的、非實例化的對象, this
實際上是指 window object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.