Javascript es6类方法中的“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36489579/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:10:02  来源:igfitidea点击:

"This" within es6 class method

javascriptclassecmascript-6this

提问by Andrew Luhring

For some reason I'm getting weird values for "this" in my es6 class...

出于某种原因,我在 es6 类中为“this”获得了奇怪的值...

'use strict';
class Clicker {
  constructor(element) {
    this.count = 0;
    this.elem = element;
    this.elem.addEventListener('click', this.click);
    
    // logs Clicker { count:0, elem: button#thing} as expected
    console.log(this);
  }

  click() {
    // logs <button id="thing">...</button> as unexpected...
    console.log(this);
    this.count++;
  }
}


var thing = document.getElementById('thing');
var instance = new Clicker(thing);
<button id="thing">Click me</button>

Question:

题:

Why is the "this" inside of of the Clickers' click method referring to the dom node rather than ... itself?

为什么 Clickers 的 click 方法中的“this”指的是 dom 节点而不是 ... 本身?

More importantly, how do I refer to Clickers' count property from within its' click method if I can't use "this" to do it?

更重要的是,如果我不能使用“this”来做到这一点,我如何从它的“click”方法中引用 Clickers 的 count 属性?

回答by jfriend00

Why is the "this" inside of of the Clickers' click method referring to the dom node rather than ... itself?

为什么 Clickers 的 click 方法中的“this”指的是 dom 节点而不是 ... 本身?

Because the specification for .addEventListener()is to set the thispointer to the DOM element that caught the event. That's how it is designed to work.

因为规范.addEventListener()是设置this指向捕获事件的DOM元素的指针。这就是它的工作原理。



When passing a method as a callback where you want to override the value of this, you can use .bind()to force the desired value of thiswith it:

当将方法作为回调传递给您想要覆盖 的值时this,您可以使用它.bind()来强制所需的值this

this.elem.addEventListener('click', this.click.bind(this));

Explanation:

解释:

All function calls in Javascript set a new value of thisaccording to how the function is called. See this explanationfor further info on that basic set of rules.

Javascript 中的所有函数调用都会this根据函数的调用方式设置一个新值。有关基本规则集的更多信息,请参阅此说明

On top of that, when you do this:

最重要的是,当你这样做时:

this.elem.addEventListener('click', this.click);

You are just getting the this.clickmethod and passing that method alone to addEventListener(). The value of thiswill be completely lost. It's as if you are doing this:

您只是获取this.click方法并将该方法单独传递给addEventListener(). 的价值this将完全丧失。就好像你在这样做:

var m = this.click;     // m here is just a reference to Clicker.prototype.click
this.elem.addEventListener('click', m);

On top of this, .addEventListener()is specifically built to set it's own value of thiswhen it calls the callback (to point thisat the element creating the event).

最重要的是,.addEventListener()它专门用于this在调用回调时设置它自己的值(指向this创建事件的元素)。

So, you can use .bind()as shown above to force the proper value of thisto be in place when your method is called.

因此,您可以使用.bind()如上所示this的方法在调用方法时强制使用适当的值。



For reference, you may find this description of the six ways that thisis setfor a function call in Javascript to be useful.

作为参考,您可能会发现在 Javascript 中为函数调用设置的六种方式的描述this很有用。



Other Options

其他选项

I find .bind()to be the clearest way of defining this, but you could also use either a local anonymous function:

我发现.bind()这是定义它的最清晰的方法,但您也可以使用本地匿名函数:

var self = this;
this.elem.addEventListener('click', function() {
    self.click();
});

or in ES6, an arrow function:

或者在 ES6 中,一个箭头函数:

this.elem.addEventListener('click', () => this.click());

The arrow function will preserve the value of thisfor you automatically to avoid needing the selfreference used in the prior example.

箭头函数将this自动为您保留 的值,以避免需要self前面示例中使用的引用。