-2

Given this object:

var myObject = {name: 'David', date: '11/13/2014'};

I want my constructor to set its object properties based on myObject:

function myClass(_object){
    // set given object's properties here
}

I want to set the properties through a loop, so I wont have to set every property by hand - because the object will be dynamic.

I'm looking for a cross-browser solution.

Orel Biton
  • 3,478
  • 2
  • 15
  • 15

1 Answers1

1

Perhaps what you want is this:

function MyClass(_object) {
  for (var p in _object) {
    if (_object.hasOwnProperty(p)) {
      this[p] = _object[p];
    }
  }
}

Don't forget to use new:

var obj = new MyClass(myObject);

Fiddle

Jonathan
  • 8,771
  • 4
  • 41
  • 78
ntalbs
  • 28,700
  • 8
  • 66
  • 83