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.c = 's';
var instance2 = new SuperType();

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.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s