问题
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