/** * 對象、數組變化監聽(增刪改) * @author w-bing * @date 2020-04-22 * @param {Object} obj * @param {Function} cb * @return {Proxy} */ function deepProxy(obj, cb) { if (typeof obj === 'object') { for (let key in obj) { if (typeof obj[key] === 'object') { obj[key] = deepProxy(obj[key], cb); } } } return new Proxy(obj, { /** * @param {Object, Array} target 設置值的對象 * @param {String} key 屬性 * @param {any} value 值 * @param {Object} receiver this */ set: function (target, key, value, receiver) { if (typeof value === 'object') { value = deepProxy(value, cb); } let cbType = target[key] == undefined ? 'create' : 'modify'; //排除數組修改length回調 if (!(Array.isArray(target) && key === 'length')) { cb(cbType, { target, key, value }); } return Reflect.set(target, key, value, receiver); }, deleteProperty(target, key) { cb('delete', { target, key }); return Reflect.deleteProperty(target, key); } }); } // 數組測試 let a = deepProxy([], (type, data) => { console.log(type, data); }); a.push(1) a.push({ a: 1 }) // 對象測試 let b = deepProxy({}, (type, data) => { console.log(type, data); }); b.name = '大花貓花大'; b.info = { age: 10, data: { data: { data: { text: 1 } } } } delete b.info.age;