gpt4 book ai didi

javascript - 在 CustomElement 中引用 self (this)

转载 作者:行者123 更新时间:2023-11-28 17:43:15 24 4
gpt4 key购买 nike

我正在使用这个polyfill在 JavaScript 中实现自定义元素。然而,self 变量在我的方法中引用 Window,除非我首先调用 const self = this

任何人都可以解释一下为什么这对我来说是这样吗?也许可以建议一种更好的方法来访问方法中的自定义元素实例?

class DocumentPreview extends HTMLElement {
constructor(self, documents) {
self = super(self);
self.documents = documents || [];
self.innerHTML = Handlebars.templates['document_preview']();
}

connectedCallback() {
// if I don't do this first ...
const self = this; // <<----------------------------------
console.log("connected now");
document.addEventListener('mqttsub', function(event) {
// ... onMessage is undefined here:
self.onMessage(event.detail);
});
}

disconnectedCallback() {
console.log("disconnected");
}

onMessage(message) {
// Same story ...
const self = this; // <<----------------------------------
Promise.resolve(true)
.then(json("/documents/"))
.then(ds => ds
.filter(x => x.name==message.payload)
.reduce((x, y) => y, undefined)
)
.then(d => json(sprintf("/document/%d/", d.id))())
// ... here:
.then(d => self.renderDocuments(d))
.catch(console.log);
}

renderDocuments(d) {
console.log('render', d);
}
}

最佳答案

尝试使用 bind() 在构造函数中绑定(bind)方法 onMessage()renderDocuments(),如 this.methodName 中所示= this.methodName.bind(this)。这样您就可以通过 this 访问属性和方法。

class DocumentPreview extends HTMLElement {
constructor(documents) {
super();

this.documents = documents || [];
this.innerHTML = Handlebars.templates['document_preview']();

this.onMessage = this.onMessage.bind(this);
this.renderDocuments = this.renderDocuments.bind(this);
}

connectedCallback() {
document.addEventListener('mqttsub', this.onMessage);
}

disconnectedCallback() {
console.log("disconnected");
}

onMessage(event) {
const { detail: message } = event;

Promise.resolve(true)
.then(json("/documents/"))
.then(ds => ds
.filter(x => x.name==message.payload)
.reduce((x, y) => y, undefined)
)
.then(d => json(sprintf("/document/%d/", d.id))())
// ... here:
.then(d => this.renderDocuments(d))
.catch(console.log);
}

renderDocuments(d) {
console.log('render', d);
}
}

希望有帮助!

关于javascript - 在 CustomElement 中引用 self (this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47425643/

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