項目實踐倉庫javascript
https://github.com/durban89/typescript_demo.git tag: 1.2.2
爲了保證後面的學習演示須要安裝下ts-node,這樣後面的每一個操做都能直接運行看到輸出的結果。java
npm install -D ts-node
後面本身在練習的時候能夠這樣使用node
npx ts-node 腳本路徑
學習如何在JavaScript里正確使用this就比如一場成年禮。 因爲TypeScript是JavaScript的超集,TypeScript程序員也須要弄清 this工做機制而且當有bug的時候可以找出錯誤所在。 幸運的是,TypeScript能通知你錯誤地使用了 this的地方。 若是你想了解JavaScript裏的 this是如何工做的,那麼首先閱讀Yehuda Katz寫的Understanding JavaScript Function Invocation and "this"。 Yehuda的文章詳細的闡述了 this的內部工做原理,所以這裏只作簡單介紹。git
JavaScript裏,this的值在函數被調用的時候纔會指定。 這是個既強大又靈活的特色,可是你須要花點時間弄清楚函數調用的上下文是什麼。 但衆所周知,這不是一件很簡單的事,尤爲是在返回一個函數或將函數當作參數傳遞的時候。程序員
下面看一個例子:github
let deck = { suits: [ 'hearts', 'spades', 'clubs', 'diamods' ], cards: Array(52), createCardPicker: function () { return function () { 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);
能夠看到createCardPicker是個函數,而且它又返回了一個函數。 若是咱們嘗試運行這個程序,會獲得以下相似錯誤提示typescript
$ npx ts-node src/function_4.ts Cannot read property '2' of undefined
由於 createCardPicker返回的函數裏的this被設置成了window而不是deck對象。 由於咱們只是獨立的調用了 cardPicker()。 頂級的非方法式調用會將 this視爲window。 (注意:在嚴格模式下, this爲undefined而不是window)。爲了解決這個問題,咱們能夠在函數被返回時就綁好正確的this。 這樣的話,不管以後怎麼使用它,都會引用綁定的'deck'對象。 咱們須要改變函數表達式來使用ECMAScript 6箭頭語法。 箭頭函數能保存函數建立時的 this值,而不是調用時的值:npm
let deck = { suits: [ 'hearts', 'spades', 'clubs', 'diamods' ], cards: Array(52), createCardPicker: function() { 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(); console.log("card: " + pickedCard.card + " of " + pickedCard.suit);
運行後獲得的結果以下dom
$ npx ts-node src/function_4.ts card: 10 of hearts
TypeScript會警告你犯了一個錯誤,若是你給編譯器設置了--noImplicitThis標記。 它會指出 this.suits[pickedSuit]裏的this的類型爲any。函數
本實例結束實踐項目地址
https://github.com/durban89/typescript_demo.git tag: 1.2.3