Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a object in javascript that has a 'init' method with optional name/value pairs

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.

like image 204
Blankman Avatar asked Dec 06 '25 06:12

Blankman


2 Answers

var myObject = {
  init: function(options) {
    this.foo = options.foo || 'some default';
    this.bar = options.requiredArg;

    if (!this.bar) raiseSomeError();
  }
}
like image 91
Alex Wayne Avatar answered Dec 07 '25 20:12

Alex Wayne


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"} )
like image 20
Anon Avatar answered Dec 07 '25 21:12

Anon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!