I've been trying to write an extend function so I can have bunch of settings in my app that can be overridden by the user by passing in a options object to the constructor.
I开发者_运维百科 need something like below....but the problem with this code is that an object doesn't have a length property (that might not be the only thing wrong with the code below).
Any ideas? How do you implement this. I've had a good Google and a look at the jQuery source but I can't figure how it's working:
extend : function() {
for(var i = 0; i < options.length; ++ i) {
if(options[i] in this.settings) {
this.settings[options[i]] = options[i];
}
}
}
You should enumerate the object properties, you can use the for-in
statement for that purpose, for example:
var obj = {
// ...
extend : function(options) {
for(var i in options) {
if (options.hasOwnProperty(i)) {
this.settings[i] = options[i];
}
}
},
settings: {foo:1}
//...
};
obj.extend({ bar: 2});
obj.settings; // {foo:1, bar:2}
The hasOwnProperty
method is used to check if the enumerated property exist physically in the object, because the for-in
can statement visit inherited properties.
精彩评论