javascript 在 underscore.js 中扩展对象的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28928240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best practice to extend objects in underscore.js
提问by Sebastian
I know that extending objects is done via the
我知道扩展对象是通过
_.extend(parent, child);
method.
方法。
I've seen different places in the web where people are extending objects in a special way in underscore.js
我在网络上的不同地方看到人们在 underscore.js 中以特殊方式扩展对象
_.extend({}, this, child);
Why do they do that?
他们为什么这样做?
回答by syed imty
According to the underscore documentation, The api of _.extend method is
根据下划线文档,_.extend方法的api是
_.extend(destination, *sources)
First Sample
第一个样品
_.extend(parent, child);
In this sample code, you are actually extending the properties from child object to parent object. Here the parent object is modified.
在此示例代码中,您实际上是将属性从子对象扩展到父对象。这里修改了父对象。
Second Sample
第二个样本
_.extend({}, parent, child);
In case you don't want to modify the parent object, and still want both the properties from parent and child. You can use this one. Here you are extending parent object, and child object to a new object.
如果您不想修改父对象,但仍需要父对象和子对象的属性。你可以用这个。在这里,您将父对象和子对象扩展到一个新对象。
回答by meagar
Take this example:
拿这个例子:
myConfig = { name: 'bob' }
yourConfig = { name: 'sam' }
_.extend(myConfig, yourConfig);
Now, myConfig
is clobbered. I've overwritten the original value of myConfig.name
, and I can never get it back.
现在,myConfig
被破坏了。我已经覆盖了 的原始值myConfig.name
,而且永远无法恢复。
In order to preserve myConfig
and yourConfig
, I need to combine both into a 3rd object:
为了保留myConfig
and yourConfig
,我需要将两者组合成第三个对象:
myConfig = { name: 'bob' }
yourConfig = { name: 'sam' }
sharedConfig = _.extend({}, myConfig, yourConfig);
回答by Mukesh Soni
Underscore's extend method overwrites the first argument passed to it. But most of the times you don't want that. You just want another object where the second is extended with method of the first.
Underscore 的扩展方法覆盖传递给它的第一个参数。但大多数时候你不想要那样。您只需要另一个对象,其中第二个对象使用第一个方法扩展。
So you pass an empty object as the container object for the result.
所以你传递一个空对象作为结果的容器对象。
var grandChild = _.extend({}, parent, child);
var grandChild = _.extend({}, parent, child);