gpt4 book ai didi

javascript - 从javascript类中的对象访问类的 `this`

转载 作者:行者123 更新时间:2023-12-05 01:54:56 26 4
gpt4 key购买 nike

代码结构非常简单:

class A {
b = 1
c = {
d () {
console.log(this.b) //=> undefined
//how can i access b here?
}
}
}

我更喜欢一个不太复杂的解决方法,因为这是我正在处理的项目的核心代码段

最佳答案

你可以使用 arrow function在声明函数的地方保留 this:

class A {
b = 1
c = {
d: () => console.log(this.b)
}
}

const a = new A;
a.c.d();

关于javascript - 从javascript类中的对象访问类的 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70429088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com