How to bind 'this' to an object arrow function?

筅森魡賤 提交于 2021-01-29 12:30:22

问题


Let us suppose we have an object profile with properties name and getName method (arrow function).

profile = {
    name: 'abcd',
    getName: () => {
        console.log(this.name);
    }
}

I want to call getName method by keeping the arrow function intact, and not changing it to regular function.

How can I get the output abcd by calling getName().

You can add expressions inside getName.

Will call() or bind() help? If so, how?

DO NOT CHANGE THE ARROW FUNCTION TO REGULAR FUNCTION

-- EDITED --

I just want to ask how can we use arrow functions inside objects so that it reflect the results as we will get in regular functions.

It was just an interview question.


回答1:


Without changing it to a regular function, the only way to get to the name property from the inner function is through accessing the outer variable name, which is profile:

const profile = {
    name: 'abcd',
    getName: () => {
        console.log(profile.name);
    }
}

profile.getName();


来源:https://stackoverflow.com/questions/52113035/how-to-bind-this-to-an-object-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!