jquery extend - array of objects
Say I have a Form object which has an array of Tab objects.
var Tab = function (options) {
return ($jQuery.extend(true, {
开发者_StackOverflow中文版 id: 'foo',
title: 'Foo'
}, options));
}
var Form = function (options) {
return ($jQuery.extend(true, {
id: 'foo',
tabs: [new Tab()]
}, options));
}
I can use this:
var myForm = new Form({tabs: [new Tab({id: 'bar'}), new Tab({title: 'Bar'}), new Tab({id: 'bar', title: 'Bar'})]});
To get:
myForm.tabs[0] => {id: 'bar', title: 'foo'}
myForm.tabs[1] => {id: 'foo', title: 'Bar'}
myForm.tabs[2] => {id: 'bar', title: 'Bar'}
But is it possible to somehow do this:
var myForm = new Form({tabs: [{id: 'bar'}, {title: 'Bar'}, {id: 'bar', title: 'Bar'}]});
And get the same result?
You can loop over the tabs and check whether they are a Tab
object, e.g. (untested):
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));
}
Reference: instanceof
精彩评论