您现在的位置是:首页 > 文章详情

TypeScript基础入门 - 函数 - this(二)

日期:2018-08-18点击:313

转载

TypeScript基础入门 - 函数 - this(二)

项目实践仓库

https://github.com/durban89/typescript_demo.git tag: 1.2.3

为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接运行看到输出的结果。

npm install -D ts-node

后面自己在练习的时候可以这样使用

npx ts-node 脚本路径

函数

this

学习如何在JavaScript里正确使用this就好比一场成年礼。 由于TypeScript是JavaScript的超集,TypeScript程序员也需要弄清 this工作机制并且当有bug的时候能够找出错误所在。 幸运的是,TypeScript能通知你错误地使用了 this的地方。 如果你想了解JavaScript里的 this是如何工作的,那么首先阅读Yehuda Katz写的Understanding JavaScript Function Invocation and "this"。 Yehuda的文章详细的阐述了 this的内部工作原理,因此这里只做简单介绍。

this参数

继续上篇文章【TypeScript基础入门 - 函数 - this(一)

this.suits[pickedSuit]的类型依旧为any。 这是因为 this来自对象字面量里的函数表达式。 修改的方法是,提供一个显式的 this参数。 this参数是个假的参数,它出现在参数列表的最前面,如下

function f(this: void) {     // 确保`this`在这个独立功能中无法使用 }

我们添加一些接口,Card 和 Deck,让类型重用能够变得清晰简单些,代码如下

interface Card {     suit: string;     card: number; } interface Deck {     suits: string[];     cards: number[];     createCardPicker(this: Deck): () => Card; } let deck: Deck = {     suits: [         'hearts',         'spades',         'clubs',         'diamods'     ],     cards: Array(52),     createCardPicker: function (this: Deck) {         return () => {             let pickedCard = Math.floor(Math.random() * 52);             let pickedSuit = Math.floor(pickedCard / 13);             return {                 suit: this.suits[pickedCard],                 card: pickedCard % 13,             }         }     } } let cardPicker = deck.createCardPicker(); let pickedCard = cardPicker(); console.log("card: " + pickedCard.card + " of " + pickedCard.suit);

运行后得到的结果类似如下

$ npx ts-node src/function_5.ts card: 3 of diamods


现在TypeScript知道createCardPicker期望在某个Deck对象上调用。 也就是说 this是Deck类型的,而非any,因此--noImplicitThis不会报错了。

本实例结束实践项目地址

https://github.com/durban89/typescript_demo.git tag: 1.2.4
原文链接:https://yq.aliyun.com/articles/629601
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章