[英]JavaScript Classes: Accessing method from within an Object's function property
我想知道是否有可能有人知道我遇到的問題的解決方案。 假設我們有以下 JavaScript class:
class foo {
// Class Method.
makeNoise() {
console.log("bar");
}
// Class Object
classObject = {
makeASound: function() {
makeNoise();
}
}
}
現在,如果我打電話給:
var foo = new foo();
foo.classObject.makeASound();
我會得到一個錯誤,說 makeNoise 沒有定義。 使用“這個”。 不起作用,因為在這種情況下,它會在 classObject 中查找 function,因此會拋出“不是函數”錯誤。 無論如何都可以從對象的 function 中訪問 makeNoise。
您需要使用箭頭 function以避免創建新上下文,然后使用關鍵字this
才能正確訪問 class 的makeNoise
方法
class Foo {
makeNoise() {
console.log("bar");
}
classObject = {
makeASound: () => { // arrow function for lexical scope
this.makeNoise(); // using `this` to refer to the Foo method
},
};
}
如果願意,您也可以使用Function.bind()
試試this.makeNoise()
classObject = {
makeASound: () => {
this.makeNoise();
}
}
更新:如果我們使用箭頭 function 表示makeASound
,我們可以保留我們與父 class this
綁定。 GMaiolo 的回答是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.