创建永远不会失去绑定的方法

问题描述 投票:1回答:2

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

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 custom-element
2个回答
6
投票

这就是JavaScript this绑定的工作原理。

你可以这样读:THIS (YDKJS)基本上,函数中this的值取决于如何调用该函数。因此,您需要通过使用bind()方法或将this定义为箭头函数(箭头函数词法绑定其上下文),明确地将foo值绑定到函数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 ); }
}

0
投票

这是定义不可绑定方法的另一种变体,也可以使用:

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

  foo = (function() {
    console.log( this );
  }).bind( this )
}
© www.soinside.com 2019 - 2024. All rights reserved.