Reading an excerpt from Google developer insights: https://developers.google.com/speed/articles/optimizing-javascript#initializing-instance-variables
Place instance variable declaration/initialization on the prototype for instance variables with value type (rather than reference type) initialization values (i.e. values of type number, Boolean, null, undefined, or string). This avoids unnecessarily running the initialization code each time the constructor is called. (This can't be done for instance variables whose initial value is dependent on arguments to the constructor, or some other state at time of construction.)
For Example, instead of:
foo.Bar = function() {
this.prop1_ = 4;
this.prop2_ = true;
this.prop3_ = [];
this.prop4_ = 'blah';
};
Use:
foo.Bar = function() {
this.prop3_ = [];
};
foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';
I understand the logic behind putting variables with value type into the function prototype, but aren't we running the initialization code when we have a reference variable like this.prop3_ = []; (as per Google example)? Does this not create a new array with every invocation of the constructor?