I've seen many javascript objects that have a 'init' method that you pass in values to in order to setup the object.
How do they internally handle the initializations of their private variables when passed in a array of name/value pairs like:
myObject.init( {prop1: "blah", prop2: "asdf", ..., propn: "n"} );
Specifically, some of these values can be optional, so how would you setup defaults and then override them if the name/value pair was passed in during the init.
var myObject = {
init: function(options) {
this.foo = options.foo || 'some default';
this.bar = options.requiredArg;
if (!this.bar) raiseSomeError();
}
}
This tests ok on FF5, IE8, Chrome 12, Opera v11.5. It doesn't matter what the default values are, they will be overwritten if their key is in the calling list, if not they will be left alone.
var myObject = {
prop1: 'default1',
prop2: 'default2',
prop3: 'default3',
prop4: 'default4',
prop5: 'default5',
prop6: 'default6',
init: function(options) {
for(key in options) {
if(this.hasOwnProperty(key)) {
this[key] = options[key]
}
}
}
}
myObject.init( {prop1: "blah", prop2: "asdf", prop5: "n"} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With