javascript - Web组件的自定义方法

标签 javascript html web-component custom-element

可以在自定义元素上定义自定义函数吗?

类似于:

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/

相关文章:

javascript - 如何获取将数据提供给 div 的样式的值? [MyShop电子商务]

javascript - NEON 动画动画结束事件?

javascript - 如何在javascript中创建一个元素并向其传递参数?

javascript - OLS 回归 JS 库

javascript - 通过书签在 javascript include 之前运行的函数

javascript - 如何让网站导航菜单在设定的秒数后出现?

c++ - 使用 Qt 获取页面内容

javascript - 当组件准备就绪时,如何在 Polymer 中动态注册新属性?

javascript - jqgrid 的 groupingGroupBy 函数中可以更改哪些选项?

javascript - 这是一个闭包吗?