首页 >社区问答列表 >es6对象方法简写?

es6对象方法简写?

var person = {
    name: "Nicholas",
    sayName() {
        console.log(this.name);
    }
};

var person = {
    name: "Nicholas",
    sayName:()=> {
        console.log(this.name);
    }
};

这两种写法有什么区别?

  • 三叔
  • 三叔    2016-11-09 11:36:491楼

    区别在于第一个 this 指向 person,也就是你调用 person.sayName() 时可以得到 Nicholas,第二个实际上可以看作

    var person = {
        name: "Nicholas",
        sayName: function() {
            console.log(this.name);
        }
    };

    它的 this 实际上指向的是 window 而不是 person,所以取不到对应的 name 值

    +0添加回复

  • 回复