编写Web组件类的ES5方式是什么?

Rap*_*nah 0 javascript web-component ecmascript-6

要定义自定义Web组件,我们可以扩展ES6类以访问元素的生命周期反应.

class HelloElement extends HTMLElement {
  // Monitor the 'name' attribute for changes.
  static get observedAttributes() {return ['name']; }

  // Respond to attribute changes.
  attributeChangedCallback(attr, oldValue, newValue) {
    if (attr == 'name') {
      this.textContent = `Hello, ${newValue}`;
    }
  }
}

// Define the new element
customElements.define('hello-element', HelloElement);
Run Code Online (Sandbox Code Playgroud)

ES5做同等对待的方式是什么?

小智 10

根据您的意见,我假设您的意思是ES6 语法,并允许支持自定义元素的浏览器也支持ES6定义的功能.

要模拟调用的默认ES6构造函数super(),我们可以使用Reflect.construct调用HTMLElement构造函数但使用我们的HelloElementconsutrctor中的原型.

对于继承,您需要.prototypeHelloElement构造函数设置为实例,HTMLElement并在其上定义方法和属性.通常使用use Object.create()来创建非功能性虚拟实例而不在此处调用构造函数.

您可以使用它Object.defineProperty来定义静态getter observedAttributes,但它通常只是一个静态列表,您可以简单地设置HelloElement.observedAttributes为一个属性名称数组.

function HelloElement() {
   return Reflect.construct(HTMLElement, [], HelloElement);
}
HelloElement.prototype = Object.create(HTMLElement.prototype);

// Monitor the 'name' attribute for changes.
Object.defineProperty(HelloElement, 'observedAttributes', {
  get: function() { return ['name']; }
});
// or just use HelloElement.observedAttributes = ['name']
// if it doesn't need to be dynamic

// Respond to attribute changes.
HelloElement.prototype.attributeChangedCallback = function(attr, oldValue, newValue) {
  if (attr == 'name') {
    this.textContent = `Hello, ${newValue}`;
  }
}

customElements.define('hello-element', HelloElement);

setTimeout(function() {
  document.getElementById('example').setAttribute('name', "World");
}, 1000);
Run Code Online (Sandbox Code Playgroud)
<hello-element id="example"></hello-element>
Run Code Online (Sandbox Code Playgroud)