如果這很難明白,爲什麼我們不停止使用它呢?認真的思考一下。爲什麼。不要。我們。僅僅。停止。使用。它?
使用函數式的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,這裏是把夢想照亮的地方,同爲了生活而拼搏奮鬥,大家互相幫助。新手加入即可獲得經過整理的最前沿的前端技術資料,不定時更新技術,與企業需求同步。好友都在裏面交流,每天都會有大牛定時講解前端技術!知識改變命運
點擊:加入