【发布时间】:2021-08-14 00:07:52
【问题描述】:
我有一个类,这个类有一个函数。 我想从该类的对象内部的另一个函数内部调用该函数。
代码如下:
class Animal
{
constructor(name)
{
this.name = name
}
//This is the function i want to call from inside the object below
emitSound(sound)
{
return `I am ${sound}`
}
//This is the object with functions
actions = {
eat()
{
return this.emitSound('eating');
},
sleep()
{
return this.emitSound('sleeping');
}
}
}
const animal = new Animal('Dog');
console.log(animal.actions.eat());
(此代码只是一个示例,我正在开发的应用程序是方式 更复杂)
你怎么看,它返回一个错误,说“this.emitSound()”是undefined。
它的发生是因为函数 eat() 试图从操作对象内部调用 this,不是吗?
所以我需要一种在 actions 对象 函数中调用emitSound() 函数的方法。请帮忙!!!
【问题讨论】:
标签: javascript json class object