我是Javascript和Node.js的新手,我試圖編寫代碼服從ECMAScript 6,但我無法獲得構造方法中的屬性定義,當寫代碼服從ECMAScript 6時,無法獲得在構造方法中定義的屬性ECScript 6
'use strict'
function Animal (name) {
this.name = name
}
// Animal.prototype.walk = (destination) => {
// console.log(this.name + " walk to " + destination) //undefined walk to China
// }
Animal.prototype.walk = function (destination) {
console.log(this.name + " walk to " + destination) //Cat walk to China
}
const cat = new Animal("Cat")
cat.walk('China')
I want to know the reason, thanks!
非箭頭功能不是「舊式」功能;他們是不同的風格,有不同的「這個」規則。如果你想把東西附加到原型上,繼續使用函數表達式。在ES6中也存在'class'。 – Ryan