开发者

how to implement this extend settings function

开发者 https://www.devze.com 2023-01-11 10:30 出处:网络
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'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.

0

精彩评论

暂无评论...
验证码 换一张
取 消