2017-07-18 19 views
0

我是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! 
+1

非箭頭功能不是「舊式」功能;他們是不同的風格,有不同的「這個」規則。如果你想把東西附加到原型上,繼續使用函數表達式。在ES6中也存在'class'。 – Ryan

回答

2

[...]我試圖寫代碼遵循ECMAScript中6,但我不能讓物業在構造函數方法定義,同時也可以是:雖然它可以與老寫的風格被引用用舊的書寫樣式引用

請注意,問題不在於你的「構造函數」在任何情況下都能起作用:它將在實例上定義一個name屬性。

這是事實如何在註釋和未註釋walk()方法中訪問name

箭頭功能()=>不快捷的function(){},它誕生爲避免定義成function環境的參考context一個目的。

隨着你上面的例子中,我描述它在ES5:

'use strict' 

function Animal (name) { 
    this.name = name 
} 


Animal.prototype.walk = (destination) => { 
    console.log(this.name + " walk to " + destination) //undefined walk to China 
} 

//the above ES6 will be transform to ES5 like this: 
var self = this; //reference `this` - the environment context into variable `self`. 
Animal.prototype.walk = function(destination) { 
    console.log(self.name + " walk to " + destination); 
} 


const cat = new Animal("Cat") 
cat.walk('China'); // undefined walk to China. 

我希望按照上面的例子中,你可以得知究竟this是。所以請「迴應」使用arrow function

+0

我寫了一篇關於範圍和上下文的文章,希望它能幫助:) https://kaiz.space/scope-and-cotext/ – Kai

+0

謝謝@ try-catch-finally更新我的答案:) – Kai