作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑这个基本的自定义元素:
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 );
}
是否有任何正确的方法来创建永远不会失去其绑定(bind)的方法?
最佳答案
这就是 JavaScript this
绑定(bind)的工作方式。
您可以阅读:THIS (YDKJS)基本上,函数内 this
的值取决于调用该函数的方式。因此,您需要通过使用 bind() 方法或将 foo
定义为箭头函数(箭头函数在词法上绑定(bind)它们的上下文)。
所以解决方案就是您找到的。
你可以这样做:
在你的构造函数中:
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 ); }
}
关于JavaScript:永不丢失绑定(bind)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793597/
我是一名优秀的程序员,十分优秀!