defineproperty
let index = 1;
Object.defineproperty(window, 'a', {
get() {
return index++;
}
})
console.log(a === 2 && a === 3)// true
Proxy
var a;
const target = window;
const handler = {
get(target, key) {
if(key === 'a') {
if(target[key] === 'undefind') {
target[key]=1;
}
return ++target[key];
}
return target[key];
}
}
const proxy = new Proxy(target, handler)
console.log(a === 2 && a === 3)// true
区别
- defineproperty只能对对象的某个属性做监听 (属性);Proxy可以对全对象做监听 (对象)
- defineproperty对源对象属性做修改;Proxy不会污染源对象,只是代理源对象并反回新的对象。