重視 JavaScript:徹底淘汰并消除JavaScript中的this
如果这很难明白,为什么我们不停止使用它呢?认真的思考一下。为什么。不要。我们。仅仅。停止。使用。它?
如果你读过 将90%的垃圾扔进垃圾桶后,我如何重新发现对JavaScript的爱, 当我说扔掉它时,你不会感到惊讶。this被丢弃了。再见。this不会被遗弃。
使用函数式的JavaScript,你永远不会看到this。因为你的代码永远不会包含this。你无法控制第三方库。流行的第三方库像 React, jQuery, eventemitter2会迫使你这么做。
以下这些库的例子强制去使用this。
在React中强制使用 this
// GROSS: thisclass 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
// GROSS: this$('p').on('click', function() { console.log($(this).text()) })
在eventemitter2中强制使用this
const events = new EventEmitter2({ wildcard: true })// GROSS: thisevents.on('button.*', function() { console.log('event:', this.event) }) events.emit('button.click')
this无处不在!
因此,问题是什么呢?
有个问题,如果你使用箭头函数,this是不允许使用的。有时我更喜欢写一个箭头函数来代替经典的函数。 好吧, 我 _总是_ 更喜欢写一个箭头函数。
另一个问题是this可能会被重新分配。因此,你的函数可能会因为其他人使用它而失败。
// WTF? these will produce different outputsconst say = cat => cat.speak() //=> "meow"const say = ({ speak }) => speak() //=> Error: Cannot read property 'sound' of undefined// WTF? these will produce different outputscat.speak() //=> "meow"const speak = cat.speak speak() //=> undefined
所以,让我们完全摆脱this。
不. THIS.
我创建一个简单的函数修饰符来摆脱this。 fixthis 可以解决现有存在的重新绑定问题! 安装它... 将它添加到您的库中... 使用它... ... 在这里记录bug,增加功能为这个项目做贡献https://github.com/joelnet/nothis. 这是最新版 重视javaScript系列。如果感兴趣, 请查看本系列的其它文章: 有问题请在twitter上@我 @joelnet在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')
等等! 还有一些!
import fixthis from 'nothis/fixthis'const cat = { sound: 'meow', speak: function() { return this.sound
}
}// GROSS: this is unintentionally reboundconst speak = cat.speak;
speak() //=> Error: Cannot read property 'sound' of undefined// LIT: this stays thisconst fixedCat = fixthis(cat)const speak = fixedCat.speak;
speak() //=> "meow"
我需要一些帮助...
npm install -P nothis
import nothis from 'nothis'
共同學習,寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章