
如果这很难明白,为什么我们不停止使用它呢?认真的思考一下。为什么。不要。我们。仅仅。停止。使用。它?
使用函数式的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,这里是把梦想照亮的地方,同为了生活而拼搏奋斗,大家互相帮助。新手加入即可获得经过整理的最前沿的前端技术资料,不定时更新技术,与企业需求同步。好友都在里面交流,每天都会有大牛定时讲解前端技术!知识改变命运
点击:加入
网友评论