Web组件的自定义方法

The*_*Nik 5 html javascript web-component custom-element

是否可以在自定义元素上定义自定义功能?

就像是:

var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function () { ... };

document.registerElement('custom-el', {
  prototype: proto
});
Run Code Online (Sandbox Code Playgroud)

并在元素上调用方法:

var istance = document.createElement('custom-el');
instance.customMethod();
Run Code Online (Sandbox Code Playgroud)

Sup*_*arp 8

是的当然。

您的示例可以在下面的代码片段中看到:

自定义元素 v1 的新答案

class CE extends HTMLElement {
  customMethod() {
    console.log( 'customMethod called' )
  }
}

customElements.define( 'custom-el', CE )

var instance = document.createElement( 'custom-el' )
instance.customMethod()
Run Code Online (Sandbox Code Playgroud)

自定义元素 v0 的旧答案(已弃用)

var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function() {
  console.log('customMethod called')
};

document.registerElement('custom-el', {
  prototype: proto
});
var instance = document.createElement('custom-el');
instance.customMethod();
Run Code Online (Sandbox Code Playgroud)