开发者

Can someone explain to me why this inheiritance in javascript doesnt work?

<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>
开发者_如何学Go</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 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:

  • Constructors considered mildly confusing
  • Object Oriented Programming in JavaScript
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜