徹底淘汰並消除JavaScript中的this
阿新 • • 發佈:2019-01-05
如果這很難明白,為什麼我們不停止使用它呢?認真的思考一下。為什麼。不要。我們。僅僅。停止。使用。它?
使用函式式的JavaScript,你永遠不會看到this。因為你的程式碼永遠不會包含this。你無法控制第三方庫。流行的第三方庫像 React, jQuery, eventemitter2會迫使你這麼做。
以下這些庫的例子強制去使用this。
在React中強制使用 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
//
$('p').on('click', function() {
console.log($(this).text())
})
在eventemitter2中強制使用this
const events = new EventEmitter2({ wildcard: true })
//
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。 更多函式修飾符見.
在建立nothis之後,我建立一個包並在我的專案中使用它。
你覺得this是什麼樣的?
在React中使用nothis
import React from 'react'
import nothisAll from 'nothis/nothisAll'
//
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 })
// 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
}
}
// GROSS: this is unintentionally rebound
const speak = cat.speak;
speak() //=> Error: Cannot read property 'sound' of undefined
// LIT: this stays this
const fixedCat = fixthis(cat)
const speak = fixedCat.speak;
speak() //=> "meow"
安裝它...
npm install -P nothis
將它新增到你的庫中...
import nothis from 'nothis'
使用它
自己是一個五年的前端工程師
如果你也是一個前端黨,無論是在學習前端開發,還是已經工作的,這裡推薦一下我們的前端學習交流群:731771211,這裡是把夢想照亮的地方,同為了生活而拼搏奮鬥,大家互相幫助。新手加入即可獲得經過整理的最前沿的前端技術資料,不定時更新技術,與企業需求同步。好友都在裡面交流,每天都會有大牛定時講解前端技術!知識改變命運
點選:加入