2015-06-04 43 views
2

我们要声明的设置的集合在一个插件来使用:

var settings = { x: 0, y: 1 }; 

,然后扩展/在一个电话与用户选项覆盖它们:

function x(opts) { 
    opts = $.extend(settings, opts); 
... 
x({ y: 2 }); 

...所有的伟大工程除了当你窝选项:

var settings = { x: 0, y: 1, files: { path: '/', names: { xml: 'x', kml: 'k' } } } 

x({ files: { path: '/tmp' } }); 

其中湿巾出files这样的名字都没有了内容。

我的兴趣是只指定文件路径,但$.extend是不够聪明来实现这一点。还是它?这通常如何处理?

回答

2

它已经被使用的$.extend深参数来实现:

jQuery.extend([deep ], target, object1 [, objectN ]) 

例如:

var settings = { 
 
    x: 0, 
 
    y: 1, 
 
    files: { 
 
    path: '/', 
 
    names: { 
 
     xml: 'x', 
 
     kml: 'k' 
 
    } 
 
    } 
 
}; 
 

 
function x(opts) { 
 
    opts = $.extend(true, settings, opts); 
 
    console.dir(opts); 
 
} 
 

 
x({ 
 
    files: { 
 
    path: '/tmp' 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
 

 
<!-- open your browser's console to see the output -->

+0

真棒!非常感谢 – ekkis