<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>模拟一个数据监测你</title>
</head>
<body>
<script type="text/javascript">
let data = {
name: "尚硅谷",
address: "北京",
};
// 创建一个监视实力对象 用于监测data 中属性的变化
const obs = new Observer(data);
console.log(obs);
// 准备一个vm 实力对象
let vm = {};
vm._data = data = obs;
function Observer(obj) {
//汇总对象中所有的书香形成一个数组
const keys = Object.keys(obj);
//遍历
keys.forEach((k) => {
Object.defineProperty(this, k, {
get() {
return obj[k];
},
set(value) {
console.log("$(k)被改变了,我要去解析模版生成虚拟dom");
obj[k] = value;
},
});
});
}
</script>
</body>
</html>