Gerard Simpson
Gerard Simpson

Reputation: 2126

Javascript invoke constructor function once when object instantiated with new

I am instantiating an object in javascript using a constructor. Like so:

var Constructor = function(){
    this.property1 = "1";    
}
var child = new Constructor();
console.log(child) // Constructor {property1: "1"}

I would like a method to be invoked once whenever a child object is instantiated via the new keyword. I would like this method to only be available to the Constructor.

This is what I have come up with so far:

var Constructor = function(property2){
    this.property1 = "1";
    (function(){ this.property2 = property2}).call(this);
}
var child = new Constructor("2")
console.log(child) // Constructor {property1: "1", property2: "2"}

Is this the correct way to approach this problem in Javascript? Is there a cleaner or more robust way that I could approach this problem?

Upvotes: 0

Views: 77

Answers (1)

Oriol
Oriol

Reputation: 288310

What you are doing seems kind of useless because you could directly use

var Constructor = function(property2) {
  this.property1 = "1";
  this.property2 = property2;
};

But if your constructor does complex things and what you want is splitting them into parts for better abstraction, then personally I would take these parts outside in order to have a cleaner constructor:

var Constructor = (function() {
  function someLogic(instance, value) {
    instance.property2 = value;
  }
  return function Constructor(property2) {
    this.property1 = "1";
    someLogic(this, property2);
  };
})();

Upvotes: 1

Related Questions