watch js实现
使用 MutationObserver 监听 DOM 变化
MutationObserver 是 JavaScript 提供的 API,用于监视 DOM 树的变化。通过创建观察者实例并指定目标节点,可以捕获节点属性、子节点或内容的变化。
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
console.log('DOM 变化:', mutation.type);
});
});
observer.observe(document.body, {
attributes: true, // 监听属性变化
childList: true, // 监听子节点变化
subtree: true // 监听所有后代节点
});
监听对象属性的变化(Proxy)
Proxy 可以拦截对象的操作,例如属性读取、赋值等。通过定义 setter 和 getter,可以实现对对象属性的监听。

const target = { value: 1 };
const handler = {
set(obj, prop, newValue) {
console.log(`属性 ${prop} 从 ${obj[prop]} 变为 ${newValue}`);
obj[prop] = newValue;
return true;
}
};
const watchedObj = new Proxy(target, handler);
watchedObj.value = 2; // 输出: "属性 value 从 1 变为 2"
监听数组变化
通过重写数组的 push、pop 等方法,可以监听数组的变更。结合 Proxy 或自定义方法实现。

const array = [1, 2, 3];
const arrayPrototype = Array.prototype;
const modifiedArray = Object.create(arrayPrototype);
['push', 'pop', 'splice'].forEach(method => {
modifiedArray[method] = function(...args) {
console.log(`数组调用了 ${method} 方法`);
return arrayPrototype[method].apply(this, args);
};
});
Object.setPrototypeOf(array, modifiedArray);
array.push(4); // 输出: "数组调用了 push 方法"
监听事件(EventTarget)
通过 addEventListener 监听标准 DOM 事件(如 click、input),适用于用户交互或浏览器事件的监听。
document.getElementById('myButton').addEventListener('click', (event) => {
console.log('按钮被点击', event.target);
});
监听变量变化(Object.defineProperty)
适用于旧版浏览器或 Vue 2.x 的数据绑定实现方式,通过定义属性的 getter 和 setter 监听变化。
let _value = 1;
const obj = {};
Object.defineProperty(obj, 'value', {
get() { return _value; },
set(newValue) {
console.log(`值从 ${_value} 变为 ${newValue}`);
_value = newValue;
}
});
obj.value = 2; // 输出: "值从 1 变为 2"






