javascript 使用下划线的 _.extend(...) 而不覆盖目标的某些成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9256821/
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
Using underscore's _.extend(...) without overriding some of the destination's members
提问by Preslav Rachev
I would like to be able to use underscore's extend
function and implement a specific case. By default, extend
overrides any existing member of the destination with that of the source. My problem with this is that I want to keep the initialize method of both the destination and the source intact, so what I did was roughly:
我希望能够使用下划线的extend
功能并实现一个特定的案例。默认情况下,extend
用源的成员覆盖目标的任何现有成员。我的问题是我想保持目标和源的初始化方法完好无损,所以我所做的大致是:
addComponent: function(comp, init) {
var iF;
if (comp.initialize) {
iF = comp.initialize;
delete comp["initialize"];
}
_.extend(this,comp);
if (iF) {
comp.initialize = iF;
comp.initialize.call(this,init);
}
return this;
}
Is this the proper way to do it - by detaching and reattaching? I mean, I want to keep underscore intact, and I don't want to extend it with any methods, because this is a very specific case. Do you spot any potential
这是正确的方法吗 - 通过分离和重新连接?我的意思是,我想保持下划线完整,我不想用任何方法扩展它,因为这是一个非常特殊的情况。你有没有发现任何潜力
回答by biziclop
Just a quick idea, _.extend
can accept multiple sources:
只是一个快速的想法,_.extend
可以接受多个来源:
_.extend( this, comp, { initialize:this.initialize });
回答by Barbara Jacob
I am really late to the party, but _.defaults
is what you were looking for.
我参加聚会真的很晚,但这_.defaults
正是您要找的。