javascript - 在不修改的情况下扩展对象(功能扩展)

标签 javascript node.js object

我一直在使用这个扩展:

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/

相关文章:

javascript - 网站javascript.js :1 Uncaught TypeError: Cannot read property 'addEventListener' of null at sitejavascript. js:1

javascript - 为什么这个简单的 javascript/jquery 代码不能提醒选定的文本?

node.js - 使用 sinon 和 proxyquire 定位嵌套方法

javascript - 使用 Node.js 将对象转换为字符串时出现类型错误

JavaScript 对象 : How to create a working object inclusive encapsulation?

javascript - 运行样板 react 导航应用程序时的 "undefined is not an object (evaluating ' Component.router ')"

javascript - 简单例子中callback的使用值(value)

node.js - ExpressJs : Differentiating between two similar routes

javascript - 展平对象的嵌套数组,将父值添加到子值之前

c++ - 在非成员函数中访问MFC对话框的成员变量