简体   繁体   中英

In Javascript, why should instance variables with reference type be put in the constructor?

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 (ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM