簡體   English   中英

如何創建自定義內置函數的實例?

[英]How can I create instances of customized builtins?

我正在為 vanilla JS 編寫一個 JSX 工廠,但我似乎無法讓定制的內置函數工作。

如果我定義一個

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

我只能

document.createElement('x-hi')

要獲得一個實例,我怎樣才能獲得這個實例:-

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

您也可以使用普通的自定義元素來執行此操作,但您應該使用document.createElement ,因為稍后可能會在代碼中定義自定義元素。

你可能在你的工廠里做這樣的事情:

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

當在已創建的HTMLButtonElement上設置is x-hello時,您無法更改它的原型以使其成為Hello

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM