admin管理员组

文章数量:1289866

It is possible to define custom functions on custom elements?

Something like:

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

document.registerElement('custom-el', {
  prototype: proto
});

And calling the method on the element:

var istance = document.createElement('custom-el');
instance.customMethod();

It is possible to define custom functions on custom elements?

Something like:

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

document.registerElement('custom-el', {
  prototype: proto
});

And calling the method on the element:

var istance = document.createElement('custom-el');
instance.customMethod();
Share Improve this question asked Sep 11, 2016 at 18:02 TheGr8_NikTheGr8_Nik 3,2004 gold badges20 silver badges37 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

Yes, of course.

Your example works as you can see in the code snippet below:

New answer for Custom Elements v1

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

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

var instance = document.createElement( 'custom-el' )
instance.customMethod()

Old answer for Custom Elements v0 (deprecated)

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();

本文标签: javascriptCustom methods of Web componentsStack Overflow