您好我正试图在程序下运行。我有一个函数hello
,我在b
内调用它。它给了我一个错误
TypeError:无法读取属性' hello'未定义的
class ChildClass {
// constructor
constructor(param, ...args) {
this.hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
this.hello(2)
}
}
}
}
}
有谁知道我在这里做错了什么?
答案 0 :(得分:1)
问题是this
并未指向ChildClass
实例,而是指向内部a
对象。一种解决方案可能是:
class ChildClass {
// constructor
constructor(param, ...args) {
const hello = this.hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
hello(2)
}
}
}
}
}
但是,如果您不打算使用hello()
作为实例方法,则可以在私有const
中声明它并且不要将其放在this
上:
class ChildClass {
// constructor
constructor(param, ...args) {
const hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
hello(2)
}
}
}
}
}
取决于你想做什么。
或者,您可以将“真实”this
保存在const
:
class ChildClass {
// constructor
constructor(param, ...args) {
const instance = this;
this.hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
instance.hello(2)
}
}
}
}
}