直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<p class="name"></p>
<p class="age"></p>
</div>
</body>
<script src="./index.js"></script>
</html>
const user = {
name: "张三",
age: 16,
};
function showName() {
document.querySelector(".name").textContent = `姓名:${user.name}`;
}
function showAge() {
document.querySelector(".age").textContent = `年龄:${user.age}`;
}
function observer(obj) {
for (const key in obj) {
let internalValue = obj[key];
const fun = new Set();
Object.defineProperty(obj, key, {
get() {
if (window.__funcs) fun.add(window.__funcs);
return internalValue;
},
set(value) {
internalValue = value;
fun.forEach((v) => v());
},
});
}
}
observer(user);
function autoRun(fn) {
window.__funcs = fn;
fn();
window.__funcs = null;
}
autoRun(showName);
autoRun(showAge);