gpt4 book ai didi

JavaScript:永不丢失绑定(bind)的方法

转载 作者:行者123 更新时间:2023-11-30 07:49:26 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com