设计一个框架时有三种选择 1.纯运行时 2.运行时+编译时 3.纯编译时
# 一. 纯运行
就是封装一个方法 用户只需要提供正确的值 方法就会返回正确的结果 比如说我们自己封装一个 Render 函数
const obj = {
tage: "div",
children: [{ tage: "span", children: "徐涛" }],
};
function render(obj, root) {
const el = document.createElement(obj.tage);
if (typeof obj.children == "string") {
const text = document.createTextNode(obj.children);
el.appendChild(text);
} else if (obj.children) {
obj.children.forEach((v) => {
render(v, el);
});
}
root.appendChild(el);
}
render(obj, document.body);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 二. 纯运行+编译
假如有一天用户抱怨手写树形结构对象太麻烦了 而且还不直观,能不能用类似html标签的方式描述树形结构的数据对象呢。为了满足客户需求你开始思考 能不能引入编译的手段。
<div>
<span>徐涛</span>
</div>
能不能把上面的html结构编译成下面的树形对象
const obj = {
tage: "div",
children: [{ tage: "span", children: "徐涛" }],
};
这个时候编写了一个 compiler的程序它的作用就是把 html字符串编译成树形结构的数据对象
const html=`<div><span>徐涛</span></div>`
cosnt obj=compiler(html) 编译成 树形结构的对象
render(obj) 然后把结构对象放在render函数里
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 三. 纯运行时
<div>
<span>徐涛</span>
</div>
直接把上面的html结构 编程下面的 js 代码
const div = document.createElement("div");
const span = document.createElement("span");
span.innerText = "徐涛";
div.appendChild(span);
document.body.appendChild(div);
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13