箭頭函數(shù) 不能用來寫
對象方法,因為它屏蔽了this的詞法封閉環(huán)境, 在箭頭函數(shù)中的this是當(dāng)前定義這個object所在的上下文
// `this` is here
var chopper = {
owner: 'Mary',
getOwner: () => {
return this.owner; // 此處的this指向當(dāng)前chopper對象所在的上下文
}
};
如果你想在object中定義方法,可以使用傳統(tǒng)函數(shù)語法或es6的簡寫
// 傳統(tǒng)函數(shù)語法
var chopper = {
owner: 'Mary',
getOwner: function() {
return this.owner;
}
};
// or es6 語法
var chopper = {
owner: 'Mary',
getOwner() {
return this.owner;
}
};
參考:
Method_definitions
methods-in-es6-objects-using-arrow-functions