简体   繁体   English

是否存在与goog.object.extend等效的纯函数?

[英]Is there a pure functional equivalent to goog.object.extend?

Per Closure documentation : 封文件

Extends an object with another object. 用另一个对象扩展一个对象。 This operates 'in-place'; 这是“就地”操作; it does not create a new Object. 它不会创建新的对象。 Example: var o = {}; 示例:var o = {}; goog.object.extend(o, {a: 0, b: 1}); goog.object.extend(o,{a:0,b:1}); o; O; // {a: 0, b: 1} goog.object.extend(o, {b: 2, c: 3}); // {a:0,b:1} goog.object.extend(o,{b:2,c:3}); o; O; // {a: 0, b: 2, c: 3} // {a:0,b:2,c:3}

But this is not a functional approach and for many contexts a functional approach is better. 但这不是功能性方法,在许多情况下,功能性方法更好。 Does Closure offer something more modern for this? 封闭是否为此提供了更现代的功能?

eg 例如

goog.object.extend(a, b);

becomes

a = goog.object.extend(a, b);

You can create a new object by using an empty object literal to be extended with the objects that you want to copy-merge: 您可以通过使用要复制合并的对象扩展的空对象文字来创建新对象:

var x = {};
goog.object.extend(x, a, b);
a = x;

If you are extending non-plain objects, you might need to use Object.create(Object.getPrototypeOf(a)) . 如果要扩展非普通对象,则可能需要使用Object.create(Object.getPrototypeOf(a))

You could implement it yourself: 您可以自己实现它:

 var a = {}; var b = extend(a, { a: 0, b: 1 }); var c = extend(b, { b: 2, c: 3 }); console.log(a, b, c); function extend(a, b) { var result = {}; for (var x in a) if (a.hasOwnProperty(x)) result[x] = a[x]; for (var x in b) if (b.hasOwnProperty(x)) result[x] = b[x]; return result; } 

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM