Dus*_*ant 13 javascript custom-element
这段代码给出了“非法构造函数”错误,有人能告诉我为什么吗?
class MyCustomElement extends HTMLElement {
constructor(){
super();
// Other things
}
}
const myFunc = () => {
const instance = new MyCustomElement();
console.log(instance);
}
myFunc();Run Code Online (Sandbox Code Playgroud)
Dus*_*ant 16
经过几个小时的搜索,我发现您必须先注册自定义元素,然后才能创建它的实例。我不认为这是在规范中,但所有浏览器都是如此,而且错误消息也很糟糕。我希望 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();Run Code Online (Sandbox Code Playgroud)