重視 JavaScript:徹底淘汰並消除JavaScript中的this
如果這很難明白,為什麼我們不停止使用它呢?認真的思考一下。為什麼。不要。我們。僅僅。停止。使用。它?
如果你讀過 ofollow,noindex" target="_blank">將90%的垃圾扔進垃圾桶後,我如何重新發現對JavaScript的愛 , 當我說扔掉它時,你不會感到驚訝。this被丟棄了。再見。this不會被遺棄。
使用函式式的JavaScript,你永遠不會看到this。因為你的程式碼永遠不會包含this。你無法控制第三方庫。流行的第三方庫像 React , jQuery , eventemitter2 會迫使你這麼做。
以下這些庫的例子強制去使用this。
在React中強制使用 this
// :disappointed: GROSS: this class Counter extends React.Component { constructor() { super() this.increment = this.increment.bind(this) } increment() { this.setState(s => ({ count: s.count + 1 })) } render() { return ( <div> <button onClick={() => this.increment}>{this.state.count}</button> <button onClick={this.increment.bind(this)}>{this.state.count}</button> </div> ) }) }
在jQuery中強制使用this
// :disappointed: GROSS: this $('p').on('click', function() { console.log($(this).text()) })
在eventemitter2中強制使用this
const events = new EventEmitter2({ wildcard: true }) // :disappointed: GROSS: this events.on('button.*', function() { console.log('event:', this.event) }) events.emit('button.click')
this無處不在!
因此,問題是什麼呢?
有個問題,如果你使用箭頭函式,this是不允許使用的。有時我更喜歡寫一個箭頭函式來代替經典的函式。 好吧, 我 _總是_ 更喜歡寫一個箭頭函式。
另一個問題是this可能會被重新分配。因此,你的函式可能會因為其他人使用它而失敗。
// WTF? these will produce different outputs const say = cat => cat.speak() //=> "meow" const say = ({ speak }) => speak() //=> Error: Cannot read property 'sound' of undefined // WTF? these will produce different outputs cat.speak() //=> "meow" const speak = cat.speak speak() //=> undefined
所以,讓我們完全擺脫this。
不. THIS.
我建立一個簡單的函式修飾符來擺脫this。 更多函式修飾符見 .
在建立nothis之後,我建立一個包並在我的專案中使用它。
你覺得this是什麼樣的?
在React中使用nothis
import React from 'react' import nothisAll from 'nothis/nothisAll' // :fire: LIT: no this in sight! class Counter extends React.Component { state = { count: 0 } constructor() { super() nothisAll(this) } increment({ setState }) { setState(({ count }) => ({ count: count + 1 })) } render({ increment, state }) { return ( <div> <button onClick={increment}>{state.count}</button> </div> ) } }
在jQuery中使用nothis
$('p').on('click', nothis(ctx => console.log($(ctx).text())))
在eventemitter2中使用nothis
const events = new EventEmitter2({ wildcard: true }) // :fire: LIT: nothis + destructuring! events.on('button.*', nothis(({ event }) => console.log('event', event))) events.emit('button.click')
等等! 還有一些!
fixthis 可以解決現有存在的重新繫結問題!
import fixthis from 'nothis/fixthis' const cat = { sound: 'meow', speak: function() { return this.sound } } // :disappointed: GROSS: this is unintentionally rebound const speak = cat.speak; speak() //=> Error: Cannot read property 'sound' of undefined // :fire: LIT: this stays this const fixedCat = fixthis(cat) const speak = fixedCat.speak; speak() //=> "meow"
我需要一些幫助...
安裝它...
npm install -P nothis
將它新增到您的庫中...
import nothis from 'nothis'
使用它...
... 在這裡記錄bug,增加功能為這個專案做貢獻 https://github.com/joelnet/nothis .
這是最新版 重視javaScript系列 。如果感興趣, 請檢視本系列的其它文章:
有問題請在twitter上@我 @joelnet