Proxy无法直接监听基本数据类型(如字符串、数字、布尔值等),因为它们是不可变的。Proxy只能在对象级别上进行操作,而不是基本数据类型
所以,要监听基本数据类型,我们可以将基本数据包裹在对象中,并在该对象上实现监听 代码如下:
function ValueWrapper(value) {
this.value = value;
this.onChange = null;
}
ValueWrapper.prototype.setValue = function(newValue) {
console.log(1)
this.value = newValue;
console.log(3)
};
const wrapper = new ValueWrapper('Hello');
const handler = {
set(target, property, value) {
console.log(`Setting property '${property}' to '${value}'`);
target[property] = value;
if (typeof this.onChange === 'function') {
this.onChange(this.value);
}
console.log(2)
return true;
}
};
const proxyWrapper = new Proxy(wrapper, handler);
proxyWrapper.onChange = newValue => {
console.log(`Value changed: ${newValue}`);
};
- 运行
可以看到监听了字符串的变化, 同时打印顺序为1 2 3, Proxy 代理了赋值操作