粗箭头函数不能用作对象方法
Fat arrow function is not working as object method
const profile = {
name: 'Alex',
getName :() =>{
return this.name;
}
};
这里我没有得到 'Alex' 的名字。但是当我改用 function 关键字时,我得到了想要的结果。为什么?
this
带箭头函数:
它提供的显着优势是它不绑定自己的 this。换句话说,箭头函数中的上下文是词法或静态定义的。
如果您要访问对象内部的方法,则需要使用常规函数而不是箭头函数。
const profile = {
name: 'Alex',
getName :function(){
return this.name;
}
};
更多关于this
的说明,您可以访问this keyword
const profile = {
name: 'Alex',
getName :() =>{
return this.name;
}
};
这里我没有得到 'Alex' 的名字。但是当我改用 function 关键字时,我得到了想要的结果。为什么?
this
带箭头函数:
它提供的显着优势是它不绑定自己的 this。换句话说,箭头函数中的上下文是词法或静态定义的。
如果您要访问对象内部的方法,则需要使用常规函数而不是箭头函数。
const profile = {
name: 'Alex',
getName :function(){
return this.name;
}
};
更多关于this
的说明,您可以访问this keyword