好吧,假设我有以下内容:
class Something {
foo = {
a: '123',
get_a() {
return this.a;
}
};
bar = {
b: '456',
get_b() {
return this.b;
},
get_c() {
return this.get_a();
}
};
}
window.s = new Something();
window.s.bar.get_c();
如果我使用s.bar.get_b()
,它将返回“456”。在 get_b()
中,我可以引用 this.b
,它看起来是对 bar
的引用。但是,当我尝试调用 s.bar.get_c()
时,出现错误:
Uncaught TypeError: this.get_a is not a function
基于我对 this
是对 bar
的引用的理解,我认为这是有道理的。但是,我不明白需要做什么才能从 bar.get_c()
实际引用 foo.get_a()
。我尝试了各种方法,但似乎没有任何效果,除了使用 s.foo.get_a()
但我不想直接引用 s
目的。我在这里缺少什么?我开始怀疑我从根本上构建了我的类(class)错误......
编辑:不知道为什么有人觉得需要更新我的帖子以使其执行代码片段..似乎有点矫枉过正 ́_(ツ)_/́
无论如何..我应该提到的一件事:实际上,我实际上并没有从类函数之外的其他上下文中调用s.foo.get_a()
,这就是我提到的原因不想直接引用 s
对象。为了清楚起见,我只是输入了完整路径!
最佳答案
使用箭头函数
:
class Something {
foo = {
a: '123',
get_a() {
return this.a;
}
};
bar = {
b: '456',
get_b() {
return this.b;
},
get_c: () => {
return this.foo.get_a();
}
};
}
const a = new Something();
console.log(a.bar.get_c());
关于javascript - 引用具有多个对象的类中的对象和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264479/