实现说明
真正干活的是函数 safeMerge,其余都是接线。
文件的主干是一个循环——for (const key of Object.keys(patch))。
使用要点
- 守卫
key === '__proto__' || key === 'constructor' || key === '…成立时借助提前的continue直接离开。 - 演示输出是带标签的(
own property:、prototype untouched:、payload readable:),每个操作都会留下自己的一行标注。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 safeMerge。
入口签名:function safeMerge(target, patch)
核心语句
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
const parsed = JSON.parse('{"__proto__": {"admin": true}}');
Object.assign(target, parsed);
代码示例
// JSON.parse defines '__proto__' as an ordinary own property: the object's
// prototype stays Object.prototype and the payload reads back verbatim.
const parsed = JSON.parse('{"__proto__": {"admin": true}}');
console.log('own property:', Object.hasOwn(parsed, '__proto__'));
console.log('prototype untouched:', Object.getPrototypeOf(parsed) === Object.prototype);
console.log('payload readable:', parsed.__proto__.admin === true);
// Object.assign copies with [[Set]], so '__proto__' hits the setter and
// hijacks the TARGET's prototype instead of creating a property.
const target = {};
Object.assign(target, parsed);
console.log('target prototype hijacked:', Object.getPrototypeOf(target).admin === true);
console.log('Object.prototype still clean:', ({}).admin === undefined);
// Hand-rolled merges have the same hazard; reject the dangerous keys.
function safeMerge(target, patch) {
for (const key of Object.keys(patch)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
target[key] = patch[key];
}
return target;
}
const guarded = {};
safeMerge(guarded, parsed);
console.log('guarded merge keeps prototype:', Object.getPrototypeOf(guarded) === Object.prototype);