jquery extend – 对象数组
假设我有一个Form对象,它有一个Tab对象数组。
var Tab = function (options) { return ($jQuery.extend(true, { id: 'foo', title: 'Foo' }, options)); } var Form = function (options) { return ($jQuery.extend(true, { id: 'foo', tabs: [new Tab()] }, options)); }
我可以用这个:
var myForm = new Form({tabs: [new Tab({id: 'bar'}), new Tab({title: 'Bar'}), new Tab({id: 'bar', title: 'Bar'})]});
要得到:
myForm.tabs[0] => {id: 'bar', title: 'foo'} myForm.tabs[1] => {id: 'foo', title: 'Bar'} myForm.tabs[2] => {id: 'bar', title: 'Bar'}
但有可能以某种方式这样做:
var myForm = new Form({tabs: [{id: 'bar'}, {title: 'Bar'}, {id: 'bar', title: 'Bar'}]});
得到相同的结果?
您可以遍历选项卡并检查它们是否是Tab
对象,例如( 未经测试 ):
var Form = function (options) { if(options && options.tabs) { var tabs = options.tabs; for(var i = 0, l = tabs.length; i < l; ++i) { if(!(tabs[i] instanceof Tab)) { tabs[i] = new Tab(tabs[i]); } } } return ($jQuery.extend(true, { id: 'foo', tabs: [new Tab()] }, options)); }
参考: instanceof