请问一下老师关于this参数定义
interface Card {
suit: string
card: number
}
interface Deck {
suits: string[]
cards: number[]
createCardPicker (this: Deck): () => Card
}
let deck: Deck = {
suits: ['hearts', 'spades', 'clubs', 'diamonds'],
cards: Array(52),
// NOTE: 函数现在显式指定其被调用方必须是 deck 类型
createCardPicker: function (this: Deck) {
return function (this:Deck) {
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()
console.log('card: ' + pickedCard.card + ' of ' + pickedCard.suit)
我这样去定义了闭包中this要求this指向Deck,但是这个demo明明this并没有指向Deck而是Winodw,可是请问老师ts也没有提示错误。编译也通过。只是执行js报错。
请问老师关于this规范有什么作用?他什么时候会规范?