나는 polyfill을 사용하여 자바 스크립트에서 맞춤 요소를 구현하고 있습니다. 그러나 을 먼저 호출하지 않는 한 self
변수는 내 방법 내에서 Window
을 참조합니다.CustomElement 내부의 자체 (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);
}
}
생성자의'self' 매개 변수는 다른 메서드에서 액세스 할 수 없으므로 기본 범위 문제입니다. 'onMessage()'처럼 arrow 함수를 사용한다면'self' 변수가 필요하지 않습니다.'this'를 직접 사용할 수 있습니다. 이벤트 리스너 콜백과 같은 비 화살표 함수의 경우, 콜백 내에서'.bind (this)'를 사용하고'self' 대신'this'를 사용하십시오. – nnnnnn