我一直在使用这个扩展:
const extend = require('util')._extend;
但只是注意到它修改了原始对象:
> let hello = {a: 5};
> extend(hello, {poop: 'whas'})
{ a: 5, poop: 'whas' }
> hello
{ a: 5, poop: 'whas' }
我可以在不修改对象的情况下扩展对象的简洁方法是什么?
例如我希望上面的 repl session 看起来像:
> let hello = {a: 5};
> extend(hello, {poop: 'whas'})
{ a: 5, poop: 'whas' }
> hello
{ a: 5 }
最佳答案
使用Object.create
const extend = require("util")._extend;
let hello = { a: 5 };
let newObj = _extend(Object.create(hello), { poops: 'whas' });
console.log(newObj.a); // a
console.log(newObj.poops); // whas
console.log(hello.a) // 5
console.log(hello.poops) // undefined
关于javascript - 在不修改的情况下扩展对象(功能扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49095115/