我研究了 JavaScript 通过“引用传递”将对象传递给函数。当这些对象在函数内发生突变/更新时,它会影响原始对象。这很清楚!
let obj = {
a: 5
};
function test(obj) {
// Creating a copy of the object to avoid modifying the original
obj = { ...obj };
obj.a = 7;
}
test(obj);
console.log(obj.a); // 5
如果我想确保原始对象不被修改,我会在函数中进行更改之前创建它的副本。这是最好的方法,还是有更好的选择?
可以使用
Proxy
使对象只读和纯函数。
这实际上在 Vue 中用于引入只读对象。
let obj = {
a: 5
};
function makeReadonly(obj){
return new Proxy(obj, {
set(val){
throw new Error('The object is readonly');
}
});
}
function makePure(fn) {
return new Proxy(fn, {
apply(fn, thisArg, args){
return fn.apply(thisArg, args.map(x => typeof x === 'object' && x ? makeReadonly(x) : x));
}
});
}
const test = makePure(obj => {
obj.a = 7;
});
test(obj);