javascript es6 类和带有事件处理程序的“this”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32893600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
es6 classes and "this" with event handlers
提问by Shan Robertson
playing around with some es6 and ran into an issue i'm not sure how to solve. consider the following
玩一些 es6 并遇到了一个我不知道如何解决的问题。考虑以下
class Foo {
constructor ( ) {
window.addEventListener('scroll', this.watch);
}
watch ( ) {
console.log(this);
}
}
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.
里面的watch
,this
是window
对象,正如预期的那样。但我怎么指Foo
?目前我用 bind 解决了这个问题,this.watch.bind(this)
但我很想知道是否有更“合适”的 ES6 方法来实现这一点。
采纳答案by Roy Miloh
You can use arrow function.
您可以使用箭头功能。
An arrow functionexpression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value.
window.addEventListener('scroll', () => this.watch());
回答by D. Melo
The class
keyword is just a syntatic sugar for the known javascript prototype inheritance chain. The way the this attribution mechanism works is the same. Just keep thinking about the class as the good old function what works with this, so it can be attributed to the one that used the new
keyword.
该class
关键字仅仅是已知的JavaScript的原型继承链中的语法糖。这种归因机制的工作方式是相同的。只需继续将类视为与此一起使用的旧函数,因此它可以归因于使用new
关键字的那个。
E6 comes with lots of new keywords to make object oriented javascript more familiar. I'm happy with that but we all must remember that the fundamental parts are still the same, just now with some shadows for newcomers :D
E6 带有许多新关键字,使面向对象的 javascript 更加熟悉。我对此很满意,但我们都必须记住,基本部分仍然相同,只是现在对新手有一些阴影:D
Ps:
Given that you know how this
is defined in Javascript, you can use it without an alias, like self
or something like that, despite that beeing a common practice.
Ps:鉴于您知道this
在 Javascript 中是如何定义的,您可以在没有别名的情况下使用它,例如self
或类似的东西,尽管这是一种常见的做法。
回答by Andrew Odri
A pure ES6 way to handle this (in my opinion) would be to use the new Proxy object. The implementation would look something like this:
处理这个问题的纯 ES6 方式(在我看来)是使用新的Proxy object。实现看起来像这样:
class Foo {
constructor() {
let proxy = new Proxy(this, this.watch);
window.addEventListener('scroll', proxy);
}
watch(e) {
console.log(this, e.target);
}
}
I would have included a Babel REPL example, however, here is the disclaimer: Babel REPL does not support the Proxy object. Kangax's compatibility table shows support in various Javascript engines.
我会包含一个 Babel REPL 示例,但是,这里是免责声明:Babel REPL 不支持 Proxy 对象。Kangax 的兼容性表显示了对各种 Javascript 引擎的支持。