在CustomElement中引用self(this)

时间:2017-11-22 01:54:01

标签: javascript custom-element

我正在使用此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);
  }
}

2 个答案:

答案 0 :(得分:2)

尝试使用onMessage()中的renderDocuments()bind()绑定方法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); } } 访问属性和方法。

Backend MacOSX is interactive backend. Turning interactive mode on.

希望这有帮助!

答案 1 :(得分:1)

在JavaScript中,this关键字指的是当前函数的上下文。

document.addEventListener('mqttsub', function(event) {
  // this here corresponds to your function(event) {...} context
  this.onMessage(event.detail); // Will fail
});

解决此问题的一种简单方法是使用箭头功能。箭头函数默认使用外部上下文。

document.addEventListener('mqttsub', (event) => {
  // this here corresponds to the outer context = your class
  this.onMessage(event.detail);
});

否则你也可以绑定上下文

document.addEventListener('mqttsub', (function(event) {
  this.onMessage(event.detail);
}).bind(this)); // Set the function context to be the class context