简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM