如何将"this"绑定到对象箭头功能? [英] How to bind 'this' to an object arrow function?
问题描述
让我们假设我们有一个对象profile
,它具有属性name
和getName
方法(箭头功能).
Let us suppose we have an object profile
with properties name
and getName
method (arrow function).
profile = {
name: 'abcd',
getName: () => {
console.log(this.name);
}
}
我想通过保持箭头功能完整,并不将其更改为常规功能来调用getName
方法.
I want to call getName
method by keeping the arrow function intact, and not changing it to regular function.
如何通过调用getName()
获得输出abcd
.
How can I get the output abcd
by calling getName()
.
您可以在getName
内添加表达式.
You can add expressions inside getName
.
call()
或bind()
会帮助吗?如果可以,怎么办?
Will call()
or bind()
help? If so, how?
请勿将箭头功能更改为常规功能
-编辑-
我只想问一下如何在对象内部使用箭头函数,以使其像我们将在常规函数中获得的那样反映结果.
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.
这只是一个面试问题.
推荐答案
在不将其更改为常规函数的情况下,从内部函数获取name
属性的唯一方法是通过访问外部变量名称,即profile
:
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();
这篇关于如何将"this"绑定到对象箭头功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!