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参数是一个假参数,应该如何理解,为什么将this的类型定义成void就不会报错?
1 回答

料青山看我应如是
TA贡献1772条经验 获得超8个赞
其实就是一种断言而已了,就是开发者断言当前的作用域下的 this 指向某个类型,如果你不声明的话,那肯定是 any 类型。
对于你说的第二个问题,为什么设置为 void 就不会报错,前提是你不在函数中使用 this 才可以,如果使用 this 的话,诸如 this.a
之类的代码均会报错。
添加回答
举报
0/150
提交
取消