为了账号安全,请及时绑定邮箱和手机立即绑定

方法在ES6对象中:使用箭头函数

方法在ES6对象中:使用箭头函数

方法在ES6对象中:使用箭头函数在ES6中,这两项法律都是合法的:var chopper = {     owner: 'Zed',     getOwner: function() { return this.owner; }};而且,作为速记:var chopper = {     owner: 'Zed',     getOwner() { return this.owner; }}是否也可以使用新的箭头函数?在尝试类似的var chopper = {     owner: 'John',     getOwner: () => { return this.owner; }};或var chopper = {     owner: 'John',     getOwner: () => (this.owner)};我收到一条错误消息,提示该方法无法访问this。这只是语法问题,还是不能在ES6对象中使用FAT管道方法?
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

在这一行getOwner: => (this.owner)应:


var chopper = {

    owner: 'John',

    getOwner: () => this.owner

}; //here `this` refers to `window` object.

你必须声明this变成一种功能:


var chopper = {

    owner: 'John',

    getOwner() { return this.owner }

};

或:


var chopperFn = function(){


    this.setOwner = (name) => this.owner = name;

    Object.assign(this,{

        owner: 'Jhon',

        getOwner: () => this.owner,

    })


}


var chopper = new chopperFn();

console.log(chopper.getOwner());

chopper.setOwner('Spiderman');

console.log(chopper.getOwner());


查看完整回答
反对 回复 2019-05-30
  • 3 回答
  • 0 关注
  • 1466 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信