let deck = { suits: ["hearts", "spades", "clubs", "diamonds"], cards: Array(52), createCardPicker: function() { // NOTE: the line below is now an arrow function, allowing us to capture 'this' right here
return () => { let pickedCard = Math.floor(Math.random() * 52); let pickedSuit = Math.floor(pickedCard / 13); return {suit: this.suits[pickedSuit], card: pickedCard % 13};
}
}
}let cardPicker = deck.createCardPicker();let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);教程說this和this.suits[pickedSuit]的類型為any,會報錯。然后提供了一種解決方案function f(this: void) { // make sure `this` is unusable in this standalone function}教程說這里的this參數(shù)是一個假參數(shù),應該如何理解,為什么將this的類型定義成void就不會報錯?
typescript中文網(wǎng)函數(shù)一節(jié)關(guān)于this的講解
森林海
2019-01-04 21:44:16