【问题标题】:Function inside an Object inside a Class类内对象内的函数
【发布时间】: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


    【解决方案1】:

    那是因为 this 引用了 actions,因为您将其称为 actions: actions.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());

    其他选项:将函数声明为arrow functions

    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());

    【讨论】:

    • 它绝对解决了我的问题,使用箭头功能完美。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2021-05-19
    • 2013-08-03
    • 2012-05-09
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多