簡體   English   中英

無需修改即可擴展對象(功能擴展)

[英]extend object without modifying (functional extend)

我一直在使用這個擴展:

const extend = require('util')._extend;

但剛剛注意到它修改了原始對象:

> let hello = {a: 5};
> extend(hello, {poop: 'whas'})
{ a: 5, poop: 'whas' }
> hello
{ a: 5, poop: 'whas' }

我可以在不修改對象的情況下擴展對象的簡潔方法是什么?

例如,我希望上面的 repl 會話看起來像:

> 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

Object.assign是您的解決方案

const object2 = Object.assign({}, object1);

此外,如果您使用的是 ES9/ES2018,最簡單的解決方案就是使用擴展運算符。 無論如何,它通常會編譯為 Object.assign,但它的語法要簡潔得多。

let hello = {a: 5}
console.log({ ...hello, foo: 'bar' })  // { a: 5, foo: 'bar' }
console.log(hello)                     // { a: 5 }

由於到目前為止沒有人提供 ES5 解決方案,讓我試一試:

 function extend(obj1, obj2) { if (!window.JSON) return false; var _res = JSON.stringify(obj1) + JSON.stringify(obj2); return JSON.parse(_res.replace('}{', ',')); } var foo = { 0: 'apple', 1: 'banana', 2: 'peach' }; var bar = { favorite: 'pear', disliked: 'apricot' }; extend(foo, bar); // returns bar console.log(foo); // { 0: 'apple', 1: 'banana', 2: 'peach' } console.log(bar); // { 0: 'apple', 1: 'banana', 2: 'peach', favorite: 'pear', disliked: 'apricot' }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM