提问人:JRodl3r 提问时间:12/28/2014 最后编辑:isherwoodJRodl3r 更新时间:9/13/2022 访问量:83076
将 jQuery $(this) 与 ES6 箭头函数一起使用(词法 this 绑定)
Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)
问:
将 ES6 箭头函数与词法绑定一起使用非常棒。this
但是,我刚才遇到了一个问题,将它与典型的jQuery点击绑定一起使用:
class Game {
foo() {
self = this;
this._pads.on('click', function() {
if (self.go) { $(this).addClass('active'); }
});
}
}
请改用箭头函数:
class Game {
foo() {
this._pads.on('click', () => {
if (this.go) { $(this).addClass('active'); }
});
}
}
然后转换为 ES5 (self = this) 类型闭包。$(this)
有没有办法让 Traceur 忽略“$(this)”进行词法绑定?
答:
这与 Traceur 和关闭某些东西无关;这就是 ES6 的工作方式。这是您通过使用而不是 .=>
function () { }
如果要编写 ES6,则需要一直编写 ES6。你不能在某些代码行上切换它,你绝对不能抑制或改变工作方式。即使你可以,你也只会得到一些奇怪的JavaScript版本,只有你才能理解,而且在你定制的Traceur之外永远无法正常工作,这绝对不是Traceur的重点。=>
解决此特定问题的方法不是用于访问单击的元素,而是使用:this
event.currentTarget
Class Game {
foo(){
this._pads.on('click', (event) => {
if(this.go) {
$(event.currentTarget).addClass('active');
}
});
}
}
jQuery之所以提供,是因为即使在ES6之前,jQuery也并不总是能够对回调函数施加一个(即,如果它通过bind
绑定到另一个上下文。event.currentTarget
this
评论
.on
this
event.currentTarget
this
event.currentTarget
this
event.currentTarget
this
class X
X.prototype
var
var x = this;
this
事件绑定
$button.on('click', (e) => {
var $this = $(e.currentTarget);
// ... deal with $this
});
圈
Array.prototype.forEach.call($items, (el, index, obj) => {
var $this = $(el);
// ... deal with $this
});
(这是我为这个问题的另一个版本写的答案,在得知它是这个问题的重复之前。我认为答案相当清楚地汇集了信息,所以我决定将其添加为社区维基,尽管它在很大程度上只是其他答案的不同措辞。
你不能。这是箭头函数的一半,它们关闭而不是拥有自己的,这是由它们的调用方式设置的。对于问题中的用例,如果希望在调用处理程序时由 jQuery 设置,则处理程序需要是一个函数。this
this
function
但是,如果你有理由使用箭头(也许你想用它来表达箭头之外的意思),你可以用,而不是如果你喜欢的话:this
e.currentTarget
this
class Game {
foo(){
this._pads.on('click', e => { // Note the `e` argument
if(this.go) {
$(e.currentTarget).addClass('active'); // Using it
}
});
}
}
on 事件对象与 jQuery 在调用处理程序时设置的对象相同。currentTarget
this
另一个案例
meagar 的答案是正确的,我已经投了赞成票。
但是,还有另一种情况:
$('jquery-selector').each(() => {
$(this).click();
})
可以固定为:
$('jquery-selector').each((index, element) => {
$(element).click();
})
这是jQuery中的一个历史错误,它将索引而不是元素作为第一个参数:
.each( 函数 )
function
Type:
要为每个匹配元素执行的函数。Function( Integer index, Element element )
请参见:https://api.jquery.com/each/#each-function
同时适用于 和 。.map( function )
.filter( function )
评论
正如 Meager 在回答同一个问题时所说:如果你想写 ES6,你需要一直写 ES6,
所以如果你使用的是 ES6: 的箭头函数,那么你必须使用 代替 .(event)=>{}
$(event.currentTarget)
$(this)
您还可以使用更好、更干净的方式来使用 currentTarget,例如 ,({currentTarget})=>{}
Class Game {
foo(){
this._pads.on('click', ({currentTarget}) => {
if(this.go) {
$(currentTarget).addClass('active');
}
});
}
}
最初,Rizzi Frank 在 Meagar 的回答中评论了这个想法,我觉得它很有用,我认为并非所有人都会阅读该评论,所以我将其写为另一个答案。
上一个:在闭合内使用下划线去抖动功能
评论
.on()
this
this