繁体   English   中英

JavaScript:永不丢失绑定的方法

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

考虑这个基本的自定义元素:

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

这是问题所在:

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 );

我看到只有一种解决方案是在构造函数中添加foo作为箭头函数,但在我看来这是错误的。

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

有没有正确的方法来创建永远不会失去绑定的方法?

这是怎样的JavaScript this结合的作品。

您可以阅读: THIS (YDKJS)基本上,函数内this的值取决于该函数的调用方式。 因此,您需要通过使用 bind() 方法或将foo定义为箭头函数(箭头函数在词法上绑定它们的上下文)来明确地将this值硬绑定到您的函数foo

所以解决方案就是你找到的。

你可以做:

在您的构造函数中:

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

或者(我不喜欢这个)

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

或者

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

这是定义也可以使用的不可绑定方法的另一种形式:

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