1

So I am using options to pass values to a new object in a literal object fashion.

var obj = new myObject({height:'500',width:'300');


function myObject(options){

}

I'm not sure the best route to get these values assigned to the object though so that this would work.

 function myObject(options){

...assignment...   

alert(this.width);

    }
Guesser
  • 1,769
  • 3
  • 25
  • 52
  • possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – Felix Kling Apr 05 '13 at 17:34

1 Answers1

7
function myObject(options){

   // copy the options into the current object
   for (var key in options) {
       if (options.hasOwnProperty(key)) {
           this[key] = options[key];
       }
   }

   alert(this.width);     // 300
}

var obj = new myObject({height:'500',width:'300'});

You can even an extend this concept where you can have default property values myObject, and you can override them with options object:

function myObject(options){
    // DEFAULTS
    this.name = 'Box';
    this.width = '100';
    this.height = '100';

   // copy the options into the current object
   for (var key in options) {
       if (options.hasOwnProperty(key)) {
           this[key] = options[key];
       }
   }

   alert(this.width); 
}

var obj = new myObject({height:'500',width:'300'});     // alert: 300
var obj2 = new myObject({height: '500'});               // alert: 100
Amy
  • 7,388
  • 2
  • 20
  • 31
  • I know the OP didn't say anything about "default" options, but it wouldn't be a bad idea to include some default object, with the keys that should always be assigned to the object, no matter if they're provided in `options` or not. – Ian Apr 05 '13 at 17:37
  • @wilco Yes these properties are public, unless OP wanted to keep them private, there are plenty of other answers on SO that explain how to make private variables in objects. – Amy Apr 05 '13 at 17:39
  • @sweetamylase Not that it's any better, but this is what I was thinking - http://jsfiddle.net/XpSXv/1/ – Ian Apr 05 '13 at 17:43