为了账号安全,请及时绑定邮箱和手机立即绑定

typescript中文网函数一节关于this的讲解

typescript中文网函数一节关于this的讲解

森林海 2019-01-04 21:44:16
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 之类的代码均会报错。


查看完整回答
反对 回复 2019-01-04
  • 1 回答
  • 0 关注
  • 441 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号