1

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?

2
  • "Does this not create a new array with every invocation of the constructor?" - it does, which is the point. Commented Jan 16, 2017 at 6:58
  • There is no "reference type" or "value type". Valid language types are listed in ECMA-262 §6.1. Variables have a value, the value might be a primitive value or a reference (aka Reference Specification Type). Commented Jan 16, 2017 at 7:13

1 Answer 1

2

Instance properties of reference types need to be added to the constructor otherwise when added to the prototype, each instance of the constructed object would share the same reference. It's OK when just reading information, but problem occurs when modyfing. Please check the following example

var Test = function () {
    this.foo = [];
};

Test.prototype.bar = [];

var instance1 = new Test();
var instance2 = new Test();

instance1.foo.push(1);
instance1.bar.push(1);
instance2.foo.push(2);
instance2.bar.push(2);

console.log(instance1.foo, instance1.bar); // [1], [1,2]

Although instance1.bar.push was called only once, the array has two values, because instance1.bar and instance2.bar are the same array, shared by two objects.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.