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