简体   繁体   English

JavaScript:永不丢失绑定的方法

[英]JavaScript: Method That's Never Loses Binding

Consider this basic custom element:考虑这个基本的自定义元素:

class XElement extends HTMLElement {
  constructor() { super(); }
  foo() { console.log( this ); }
} customElements.define( 'x-element', XElement );

Here is the problem:这是问题所在:

const xelem = new XElement();

/* `foo` will lose its binding to `xelem`:
*/ someButton.onclick = xelem.foo;

// These will work, but it's too verbose:
someButton.onclick = () => xelem.foo();
someButton.onclick = xelem.foo.bind( xelem );

I see only one solution is to add foo as arrow function in constructor, but it seems to me wrong.我看到只有一种解决方案是在构造函数中添加foo作为箭头函数,但在我看来这是错误的。

constructor() {
  super();
  this.foo = () => console.log( this );
}

Is there any right way to create method that will never lose its binding?有没有正确的方法来创建永远不会失去绑定的方法?

That is how JavaScript this binding works.这是怎样的JavaScript this结合的作品。

You can read this: THIS (YDKJS) Basically, the value of this inside a function depends upon how that function is invoked.您可以阅读: THIS (YDKJS)基本上,函数内this的值取决于该函数的调用方式。 So you need to explicitly hard bind the this value to your function foo by using the bind() method or defining foo as arrow function (arrow functions lexically bind their context).因此,您需要通过使用 bind() 方法或将foo定义为箭头函数(箭头函数在词法上绑定它们的上下文)来明确地将this值硬绑定到您的函数foo

So the solution is what you found.所以解决方案就是你找到的。

You can do:你可以做:

In your constructor:在您的构造函数中:

class XElement extends HTMLElement {
  constructor() { 
   super(); 
   this.foo = this.foo.bind(this);   
  }
  foo() { console.log( this ); }
}

Or (I don't like this one)或者(我不喜欢这个)

class XElement extends HTMLElement {
  constructor() { 
   super(); 
   this.foo = () => console.log(this);   
  }
}

Or或者

class XElement extends HTMLElement {
  constructor() { super(); }
  foo = () => { console.log( this ); }
}

Here is another variant of defining unbindable method that could be used too: 这是定义也可以使用的不可绑定方法的另一种形式:

class XElement extends HTMLElement {
  constructor() { super(); }

  foo = (function() {
    console.log( this );
  }).bind( this )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM