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?
this.property2 = "2";. Are you asking whetherf.call(this)is the correct way of calling a function and settingthisto a specific value? If yes, then yes.Constructorfunction. I will edit the question to reflect this