有人可以向我解释为什么javascript中的这种继承不起作用?

时间:2010-07-20 03:46:31

标签: javascript oop inheritance

<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>

输出:

This is a sub class with name Sub and variable undefined

那么子类怎么没有someVariable?我认为这就是原型制作的全部要点。

1 个答案:

答案 0 :(得分:2)

您只是将SuperClass构造函数的引用分配给SubClass.prototype,您需要使用new运算符使此SubClass.prototype对象成为{{{}的实例1}}:

SuperClass

您可能希望在上一行之后恢复//... SubClass.prototype = new SuperClass(); //.. 对象的constructor属性,因为如果您不这样做,则使用SubClass.prototype创建的实例(如{{ 1}}在您的示例中)将有一个继承的SubClass属性错误地指向sub

constructor

查看示例here

推荐文章:

相关问题