-1

This is how I create objects from a hash of properties:

var object = new function (data) {
  var self = this;
  self.property = data.property;
  self.anotherProperty = data.anotherProperty;

  self.method = function () { return 'something'; }
  self.update = function (newData) {
     //what is here ? 
     //i could have written:
     self.property = newData.property;
     self.anotherProperty = newData.anotherProperty;
     //but why not reuse the constructor?
   }
};

I wonder how to reuse this function (constructor) to update an object from hash. So that:

object.update(newData) 

would update current object properties from newData hash the same way it is done in the constructor function.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dziamid
  • 11,225
  • 12
  • 69
  • 104

1 Answers1

3

By giving the constructor a name?

function MyNotReallyClass(data){
  var self = this;
  self.property = data.property;
  self.method = function () { return 'something'; }
  self.update = MyMyNotReallyClass;
};

you can can now call

var obj = new MyNotReallyClass(data);
var obj2 = new MyNotReallyClass(data);

and

obj.update(data);

i hope this helps.. i not 100% sure, because i'm learning too.. but yeah try it ;)

edit: after reading this comment of you: "But that would return a new instance, wouldn't it? Which i don't want."

i think you can write the Update function and call it in your constructor

var object = new function (data) {
  var self = this;
  self.update = function (newData) {  
   self.property = data.property;
   self.method = function () { return 'something'; }
   // and other things You want to do in constructor and update
  }
  self.update(data);
}

;

Xaw4
  • 176
  • 2
  • 9
  • Hey, good thinking! You turned the problem upside down, cool.. This allows the function to stay anonymous. – Dziamid Aug 03 '12 at 10:16