und*_*ned 1 javascript this custom-element
考虑以下基本自定义元素:
class XElement extends HTMLElement {
constructor() { super(); }
foo() { console.log( this ); }
} customElements.define( 'x-element', XElement );
Run Code Online (Sandbox Code Playgroud)
这是问题所在:
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 );
Run Code Online (Sandbox Code Playgroud)
我看到只有一种解决方案是foo在构造函数中添加为箭头函数,但是在我看来这是错误的。
constructor() {
super();
this.foo = () => console.log( this );
}
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法来创建永远不会失去其绑定的方法?
这就是JavaScript this绑定的工作方式。
您可以阅读以下内容:THIS(YDKJS)
基本上,this函数内部的值取决于该函数的调用方式。因此,您需要通过使用bind()方法或定义为箭头函数(箭头函数按词法绑定其上下文)this来将值明确绑定到函数。foofoo
因此,解决方案就是您所发现的。
你可以做:
在您的构造函数中:
class XElement extends HTMLElement {
constructor() {
super();
this.foo = this.foo.bind(this);
}
foo() { console.log( this ); }
}
Run Code Online (Sandbox Code Playgroud)
或者(我不喜欢这个)
class XElement extends HTMLElement {
constructor() {
super();
this.foo = () => console.log(this);
}
}
Run Code Online (Sandbox Code Playgroud)
要么
class XElement extends HTMLElement {
constructor() { super(); }
foo = () => { console.log( this ); }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51 次 |
| 最近记录: |