如何创建自定义内置函数的实例?

时间:2021-04-22 08:25:39

标签: javascript dom custom-element native-web-component

我正在为 vanilla JS 编写一个 JSX 工厂,但是我似乎无法让自定义的内置函数工作。

如果我定义一个

customElements.define('x-hi', class extends HTMLElement { })

我只能

document.createElement('x-hi')

要获得一个实例,我怎样才能获得这个实例:-

customElements.define('x-hello', class extends HTMLButtonElement { }, { extends: 'button' })

1 个答案:

答案 0 :(得分:0)

class Hello extends HTMLButtonElement { }
customElements.define('x-hello', Hello, { extends: 'button' });
new (customElements.get('x-hello'))() instanceof Hello
// --> true

您也可以使用普通的自定义元素来实现,但您应该使用 document.createElement,因为自定义元素可能会在稍后的代码中定义。

您的工厂可能正在做这样的事情:

const el = document.createElement(tagName);
for (let attrName in attrs) el.setAttribute(attrName, attrs[attrName]);

在已创建的 is 上将 x-hello 设置为 HTMLButtonElement 时,您无法更改它的原型以使其成为 Hello

相关问题