本文介绍了es6类和"this"与事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
玩一些es6,遇到了一个我不确定如何解决的问题.考虑以下
playing around with some es6 and ran into an issue i'm not sure how to solve. consider the following
class Foo {
constructor ( ) {
window.addEventListener('scroll', this.watch);
}
watch ( ) {
console.log(this);
}
}
在watch
内,this
是window
对象,如预期的那样.但是,我怎么指代Foo
?目前,我可以通过bind this.watch.bind(this)
解决这个问题,但是我很想知道是否还有一种更合适的" ES6方法来实现这一目标.
Inside of watch
, this
is the window
object, as expected. But how do i refer to Foo
? Currently I get around this with bind this.watch.bind(this)
but i'd love to know if there is a more "proper" ES6 way to get this going.
推荐答案
您可以使用箭头功能.
window.addEventListener('scroll', () => this.watch());
这篇关于es6类和"this"与事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!