Javascript jqueryextend覆盖错误的值
我在插件中使用jQueryJavascript jqueryextend覆盖错误的值,javascript,jquery,Javascript,Jquery,我在插件中使用jQueryextend,覆盖默认参数。然而,我有一个问题 以下是我的默认设置数组: slider.settings = { background: { animation : { direction : 'horizontal', increment : 15 //can be any number }
extend
,覆盖默认参数。然而,我有一个问题
以下是我的默认设置数组:
slider.settings = {
background: {
animation : {
direction : 'horizontal',
increment : 15 //can be any number
}
}
}
现在,我想覆盖方向
参数。下面是我将使用extend
合并的数组:
settingsToOverwrite = {
background:{
animation:{
direction:'vertical'
}
}
}
现在,我将两者合并:
slider.settings = $.extend(slider.settings, options)
我可以看到方向值已更新。然而,增量不再存在。我知道,为了避免这个问题,我只能在第一级设置参数,但我认为这样做会使代码更加清晰。有没有办法做到这一点?如果没有,我会将所有内容更改为只有一级深度。你是对的,这显然是因为jQuery的扩展是对对象的“浅扩展”。。从而替换整个“动画”属性 要解决此问题,请使用您的白兰地花花公子:
Object.deepExtend = function(destination, source) {
for (var property in source) { // loop through the objects properties
if (typeof source[property] === "object") { // if this is an object
destination[property] = destination[property] || {};
Object.deepExtend(destination[property], source[property]); // recursively deep extend
} else {
destination[property] = source[property]; // otherwise just copy
}
}
return destination;
};
您可以按如下方式使用它:
slider.settings = Object.deepExtend(slider.settings, options);
默认情况下,
jQuery.extend()
只比较立即属性,执行“浅合并”。因为两个对象都有background
,所以它只从第二个对象获取整个background
但是,作为第一个参数,和jQuery.extend()
将执行“深度合并”
此外,由于第一个
对象
是目标
,并且将被修改和返回
,因此您可以更新滑块。设置
只需:
$.extend(true, slider.settings, options);
而且,如果您希望从合并中获得一个新对象
,则必须自己创建它:
slider.settings = $.extend(true, {}, slider.settings, options);
你有没有关于slider.settings的示例?我的意思是我不知道如何使用这个函数。谢谢。刚刚添加到回答:)这很好,但我会避免使用
参数。被调用方
,因为它将在严格模式下抛出错误。我注意到var newObj=$.extend(Obj1,Obj2)
还将修改Obj1
的内容,该内容不需要存储回退值,但添加{}
不会。这正常吗?
slider.settings = $.extend(true, {}, slider.settings, options);