JavaScript

OOP4: A hole in prototype chain

function SuperType(){
   this.a = 1;
   this.b = [2];
}
SuperType.prototype.c = 3;
SuperType.prototype.d = [4];
function SubType(){}
SubType.prototype = new SuperType();
var instance1 = new SubType();
instance1.a = 's';
instance1.b.push('s');
instance1.c = 's';
instance1.d.push('s');
var instance2 = new SuperType();
console.log(instance2.a);//1
console.log(instance2.b);//[2]
console.log(instance2.c);//3
console.log(instance2.d);//[4,'s']

For base type, this.a or SuperType.prototype.c all work like below:

var a = 1; var b = a; b = 2; console.log(a);//1

For reference type, the assigned variables will points to the same object.

var obj1 = [1]; var obj2 = obj1; obj2.push(2); console.log(obj1);//[1,2]

So here instance1.d and SuperType.prototype.d point to the same object, so they will influence each other. Then why this.b is not influenced?

this.b = [2];// equals this.b = new Array(); Array[0] = 2;

That is to say, this.b and instance1.b are separated objects.

var a = [1]; var b = [1]; a === b;// false

So to prevent this hole, just define the reference types in this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s