Javascript-如果超级类构造函数接受参数,如何初始化超级类
考虑以下Javascript代码片段Javascript-如果超级类构造函数接受参数,如何初始化超级类,javascript,prototypal-inheritance,Javascript,Prototypal Inheritance,考虑以下Javascript代码片段 var SuperClass = function(x){ this.x = x; this.a = 5; }; var SubClass = function(x){ } function IntermediateClass(){}; IntermediateClass.prototype = SuperClass.prototype; SubClass.prototype = new IntermediateClass; SubCla
var SuperClass = function(x){
this.x = x;
this.a = 5;
};
var SubClass = function(x){
}
function IntermediateClass(){};
IntermediateClass.prototype = SuperClass.prototype;
SubClass.prototype = new IntermediateClass;
SubClass.prototype.constructor = SubClass;
现在,如果我创建子类的实例,对象将不会初始化属性“a”和“x”
虽然我理解为什么会发生这种情况,但子类执行超类构造函数初始化的最干净的方法是什么?首先,代码中有一大堆错误 这将使中间类成为超类的姐妹
IntermediateClass.prototype = SuperClass.prototype;
您永远不需要这样做,构造函数
为您处理
SubClass.prototype.constructor = SubClass;
也就是说,JavaScript没有类。继承是基于对象的。你不能做你想做的事
相反,我将在一个单独的函数中提取初始化,然后从“子类”中调用它
一个更好的问题是你想完成什么。您正在尝试编写JavaScript,就像它是Java一样。并非如此。这篇文章解释了使用IntermediateClass.com的原因。可能是
SubClass.prototype.constructor = SubClass;