森林海
2019-11-18 18:25:41
當(dāng)ES6 Arrow函數(shù)似乎無法使用prototype.object將函數(shù)分配給對象時??紤]以下示例:function Animal(name, type){ this.name = name; this.type = type; this.toString = () => `${this.name} is a ${this.type}`;}var myDog = new Animal('Max', 'Dog');console.log(myDog.toString()); //Max is a Dog在對象定義中顯式使用arrow函數(shù)是可行的,但將Object函數(shù)與Object.prototype語法一起使用不能:function Animal2(name, type){ this.name = name; this.type = type;}Animal2.prototype.toString = () => `${this.name} is a ${this.type}`;var myPet2 = new Animal2('Noah', 'cat');console.log(myPet2.toString()); //is a undefined就像概念證明一樣,將Template字符串語法與Object.prototype語法結(jié)合使用確實可以:function Animal3(name, type){ this.name = name; this.type = type;}Animal3.prototype.toString = function(){ return `${this.name} is a ${this.type}`;}var myPet3 = new Animal3('Joey', 'Kangaroo');console.log(myPet3.toString()); //Joey is a Kangaroo我是否缺少明顯的東西?我覺得示例2應(yīng)該在邏輯上起作用,但是我對輸出感到困惑。我猜這是一個范圍界定的問題,但是輸出“是未定義的”讓我望而卻步。
3 回答

隔江千里
TA貢獻1906條經(jīng)驗 獲得超10個贊
箭頭函數(shù)提供了一個詞法this。它使用在this評估功能時可用的。
從邏輯上講,它等效于(以下無效代碼,因為您不能使用名為的變量this):
(function(this){
// code that uses "this"
})(this)
在您的第一個示例中,arrow函數(shù)在構(gòu)造函數(shù)中,并this指向新生成的實例。
在您的第三個示例中,未使用箭頭功能,并且標(biāo)準(zhǔn)this行為照常運行(此功能在功能范圍內(nèi))。
在第二個示例中,您使用了箭頭函數(shù),但是在評估范圍內(nèi),它this是全局/未定義的。

弒天下
TA貢獻1818條經(jīng)驗 獲得超8個贊
您可以this
在this
您打算使用的任何地方使用它。例如,假設(shè)你的對象有一個setup()
功能,增加了多種功能本身,你會這樣稱呼它:myObj.setup()
。該功能可以使用箭頭功能添加所需的功能。另一個更典型的用例是使用需要訪問this
初始上下文的回調(diào)函數(shù)。
添加回答
舉報
0/150
提交
取消