![](/img/trans.png)
[英]How to access variable name assigned to object from within class constructor in Javascript?
[英]Access `this` of a class from an object within the class in javascript
代碼結構非常簡單:
class A {
b = 1
c = {
d () {
console.log(this.b) //=> undefined
//how can i access b here?
}
}
}
我更喜歡一個不那么老套的解決方法,因為這是我正在從事的項目的核心代碼
您可以使用箭頭 function將其保留this
聲明 function 的位置:
class A { b = 1 c = { d: () => console.log(this.b) } } const a = new A; a.c.d();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.