简体   繁体   中英

How can I create instances of customized builtins?

I'm writing a JSX factory for vanilla JS, but I can't seem to get customized builtins to work.

If I define a

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

I can just

document.createElement('x-hi')

to get an instance, how can I get an instance of this:-

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

You can also do it with normal custom elements, but you should use document.createElement as the custom element may be defined later on in the code.

You're probably doing something like this in your factory:

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

When setting is to x-hello on an already created HTMLButtonElement , you can't change it's prototype to have it become a Hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM