This code work :
function class1(){
this.x5 = 5;
this.x6 = 6;
this.prototype = 5;
}
function class2(){
this.x3 = 3;
this.x4 = 4;
}
class2.prototype = new class1();
var obj1 = new class2();
alert(obj1.x5 ); // alert me 5
But why this not working :
function class1(){
this.x5 = 5;
this.x6 = 6;
this.prototype = 5;
}
function class2(){
this.x3 = 3;
this.x4 = 4;
this.prototype = new class1(); // or class2.prototype = new class1();
}
var obj1 = new class2();
alert(obj1.x5); // alert me "undefinded"
You can’t set the prototype inside of the function like that. When invoking a function with the
newoperator, then a new object is created, andthisgets set to that object. Objects don’t have a publicly accessible prototype property that you can set. Their prototype property is actually__proto__, which is not accessible (although some browsers do let you get at it).In your second example, you’re just setting a plain ol’ vanilla property named "prototype" with a value.
the
prototypeproperty on a function is also not the prototype! Confusing, eh? What it really is is something of a "prototype template". It basically means "when you create an object using this function as the constructor, set their prototype to whatever I have set in theprototypeproperty." This can be very confusing until you grok it.Also Note
Your first example doesn’t work either (try it here), you are setting the prototype property of the function after the instance was already created. So that instance was already given a different prototype object. If you created a second instance of
class2, it would alert the property correctly.