考虑这个基本自定义元素:
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()方法或将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 ); }
}
这是定义不可绑定方法的另一种变体,也可以使用:
class XElement extends HTMLElement {
constructor() { super(); }
foo = (function() {
console.log( this );
}).bind( this )
}