可以在自定义元素上定义自定义函数吗?
类似于:
var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function () { ... };
document.registerElement('custom-el', {
prototype: proto
});
然后在元素上调用方法:
var istance = document.createElement('custom-el');
instance.customMethod();
最佳答案
当然可以。
您的示例可以在下面的代码片段中看到:
自定义元素 v1 的新答案
class CE extends HTMLElement {
customMethod() {
console.log( 'customMethod called' )
}
}
customElements.define( 'custom-el', CE )
var instance = document.createElement( 'custom-el' )
instance.customMethod()
自定义元素 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();
关于javascript - Web组件的自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39439085/