我只是想把这段代码记录在某个地方。该代码使用代理来实现:
- 一个带有一组固定键的对象和
- 一个模板对象,它生成一个派生对象,该对象仅具有已分配值的模板中的这些键。
const unlock = Symbol("unlock");
const lock = (o) =>
new Proxy(o, {
get: (target, property) =>
property === unlock ? target : Reflect.get(target, property),
set: (target, key, value) =>
o.hasOwnProperty(key) ? Reflect.set(target, key, value) : true,
});
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const result = Object.assign(lock(obj1), obj2)[unlock];
console.log(result);
console.log(result === obj1);
const derived = Symbol("derived");
const template = (o) =>
new Proxy(Object.create(null), {
get: (target, property) =>
property === derived ? target : Reflect.get(target, property),
set: (target, key, value) =>
o.hasOwnProperty(key) ? Reflect.set(target, key, value) : true,
});
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const result = Object.assign(template(obj1), obj2)[derived];
console.log(result);