胖箭头功能无法用作对象方法

问题描述 投票:0回答:1
const profile = {
    name: 'Alex',
    getName :() =>{
        return this.name;
    }
};

这里我的名字不是'Alex'。但是当我改用function关键字时,我得到了期望的结果。为什么?

object ecmascript-6 this arrow-functions
1个回答
0
投票

[this具有箭头功能:

它提供的显着优势是它不绑定自身。换句话说,箭头函数内部的上下文是按词法或静态定义的。

如果要访问对象内部的方法,则需要使用常规函数而不是箭头函数。

const profile = {
    name: 'Alex',
    getName :function(){
        return this.name;
    }
};

有关this的更多说明,您可以访问this keyword

© www.soinside.com 2019 - 2024. All rights reserved.