And*_*tto 2 javascript json class object
我有一个类,这个类有一个函数。我想从该类内的对象内的另一个函数内部调用该函数。
这是代码:
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());Run Code Online (Sandbox Code Playgroud)
(此代码只是一个示例,我正在开发的应用程序要复杂得多)
如您所见,它返回一个错误,指出“ this.emitSound() ” is undefined。它的发生是因为该函数eat()试图this从 actions 对象内部调用,不是吗?
所以我需要的是一种调用动作对象emitSound()函数内部函数的方法。请帮忙!!!
那是因为this引用是因为您将其称为:actions的方法。actionsactions.eat()
一种解决方法是将bind函数添加到当前实例中 constructor :
class Animal
{
constructor(name)
{
this.name = name
this.actions.eat = this.actions.eat.bind(this);
this.actions.sleep = this.actions.sleep.bind(this);
}
//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());Run Code Online (Sandbox Code Playgroud)
其他选项:将函数声明为箭头函数:
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: () => this.emitSound('eating'),
sleep: () => this.emitSound('sleeping')
}
}
const animal = new Animal('Dog');
console.log(animal.actions.eat());Run Code Online (Sandbox Code Playgroud)