<html>
<head>
<script>
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.
You are simply assigning a reference to the
SuperClassconstructor to theSubClass.prototype, you need to use thenewoperator to make thisSubClass.prototypeobject an instance ofSuperClass:You may want to restore the
constructorproperty of theSubClass.prototypeobject after the above line, because if you don’t do it, the instances created withSubClass(likesubin your example) will have an inheritedconstructorproperty wrongly pointing toSuperClass:Check an example here.
Recommended articles: