此代码给出“非法构造函数”错误,有人可以告诉我原因吗?
class MyCustomElement extends HTMLElement {
constructor(){
super();
// Other things
}
}
const myFunc = () => {
const instance = new MyCustomElement();
console.log(instance);
}
myFunc();
经过数小时的搜索,我发现您必须注册自定义元素,然后才能创建它的实例。我认为这不是规范,但是所有浏览器都属于这种情况,错误消息也很糟糕。我希望chrome会说“您必须在实例化它之前注册一个自定义元素”,而不是“非法构造函数”,这几乎告诉我们实际上出了什么问题。
class MyCustomElement extends HTMLElement {
constructor(){
super();
// Other things
}
}
const myFunc = () => {
const instance = new MyCustomElement();
console.log(instance);
}
// Add this and it will start working
window.customElements.define('my-custom-element', MyCustomElement);
myFunc();
请注意,您可以在使用document.createElement()
定义自定义元素之前创建它。
此元素将创建为未知元素,然后仅在定义时升级到自定义元素。
class MyCustomElement extends HTMLElement {
constructor(){
super()
console.log( 'created' )
}
}
const myFunc = () => {
const instance = document.createElement( 'my-custom-element' )
console.log( instance )
document.body.appendChild( instance )
}
myFunc()
customElements.define( 'my-custom-element', MyCustomElement )