如果这很难明白,为什么我们不停止使用它呢?认真的思考一下。为什么。不要。我们。仅仅。停止。使用。它?
如果你读过 将90%的垃圾扔进垃圾桶后,我如何重新发现对JavaScript的爱, 当我说扔掉它时,你不会感到惊讶。this被丢弃了。再见。this不会被想起。
使用函数式的JavaScript,你永远不会看到this。因为你的代码永远不会包含this。你无法控制第三方库。流行的第三方库像 React, jQuery, eventemitter2会迫使你这么做。
以下这些库的例子强制去使用this。
在React中强制使用 this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 😞 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
1
2
3
4
|
// 😞 GROSS: this
$(‘p’).on(‘click’, function() {
console.log($(this).text())
})
|
在eventemitter2中强制使用this
1
2
3
4
5
6
7
8
|
const events = new EventEmitter2({ wildcard: true })
// 😞 GROSS: this
events.on(‘button.*’, function() {
console.log(‘event:’, this.event)
})
events.emit(‘button.click’)
|
this无处不在!
有个问题,如果你使用箭头函数,this是不允许使用的。有时我更喜欢写一个箭头函数来代替经典的函数。 好吧, 我 _总是_ 更喜欢写一个箭头函数。
另一个问题是this可能会被重新分配。因此,你的函数可能会因为其他人使用它而失败。
1
2
3
4
5
6
7
8
9
|
// 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import React from ‘react’
import nothisAll from ‘nothis/nothisAll’
// 🔥 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
1
|
$(‘p’).on(‘click’, nothis(ctx => console.log($(ctx).text())))
|
在eventemitter2中使用nothis
1
2
3
4
5
6
|
const events = new EventEmitter2({ wildcard: true })
// 🔥 LIT: nothis + destructuring!
events.on(‘button.*’, nothis(({ event }) => console.log(‘event’, event)))
events.emit(‘button.click’)
|
fixthis 可以解决现有存在的重新绑定问题!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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”
|
安装它…
1
|
npm install –P nothis
|
将它添加到您的库中…
1
|
import nothis from ‘nothis’
|
使用它…
… 在这里记录bug,增加功能为这个项目做贡献https://github.com/joelnet/nothis.
这是最新版 重视javaScript系列。如果感兴趣, 请查看本系列的其它文章:
转自 http://web.jobbole.com/95456/