views:

37

answers:

1

function SuperClass()
{
    var self = this;
    self.someVariable = true;
}
function SubClass()
{
    var self = this;
    self.name = "Sub";
}
SubClass.prototype = SuperClass;

var sub = new SubClass();

alert("This is a sub class with name " + sub.name + " and variable " + sub.someVariable);

</script>
</head>
<body>
</body>
</html>

output:

This is a sub class with name Sub and variable undefined

So how come sub class doesnt have someVariable? I thought thats the whole point of prototyping.

+2  A: 

You are simply assigning a reference to the SuperClass constructor to the SubClass.prototype, you need to use the new operator to make this SubClass.prototype object an instance of SuperClass:

//...
SubClass.prototype = new SuperClass();
//..

You may want to restore the constructor property of the SubClass.prototype object after the above line, because if you don't do it, the instances created with SubClass (like sub in your example) will have an inherited constructor property wrongly pointing to SuperClass:

SubClass.prototype.constructor = SubClass;

Check an example here.

Recommended articles:

CMS