我目前正在研究CustomHtmlElement,我对调用构造函数的顺序有一个误解.
例如,如果我有两个CustomHtmlElement:
class ExForm extends HTMLElement {
constructor() {
super();
console.log(`${this.getAttribute('name')} constructor ${performance.now()}`);
//debugger;
}
connectedCallback() {
console.log(`${this.getAttribute('name')} connected ${performance.now()}`);
}
}
customElements.define("ex-form", ExForm);
class ExInput extends HTMLElement {
constructor() {
super();
console.log(`${this.getAttribute('name')} constructor ${performance.now()}`);
//debugger;
}
connectedCallback() {
console.log(`${this.getAttribute('name')} connected ${performance.now()}`);
}
}
customElements.define("ex-input", ExInput);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<ex-form name="form1">
<ex-input name="input1" ></ex-input>
</ex-form>
<ex-form name="form2">
<ex-input name="input2"></ex-input>
</ex-form>
</body>
<script src="./index.js"></script>
</html>
我原以为构造函数的执行顺序是:
Form1,Input1,Form2,Input2
然而,当我执行代码时,顺序是:
Form1、Form2、Input1、Input2
有人能解释一下为什么构造函数的执行顺序和呈现给页面的HTML元素的顺序不一致吗?