【问题标题】:Fat arrow function is not working as object method胖箭头函数不能用作对象方法
【发布时间】:2019-12-17 08:55:34
【问题描述】:
const profile = {
    name: 'Alex',
    getName :() =>{
        return this.name;
    }
};

在这里,我没有得到“亚历克斯”的名字。但是当我使用 function 关键字时,我得到了期望的结果。为什么?

【问题讨论】:

标签: object ecmascript-6 this arrow-functions


【解决方案1】:

this 带箭头功能:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2018-02-01
    • 2021-06-23
    • 2019-06-27
    相关资源
    最近更新 更多