Javascript - 如果超类构造函数接受参数,如何初始化超类 [英] Javascript - how to initialize super class if super class constructor takes arguments
问题描述
考虑以下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;
SubClass.prototype.constructor = SubClass;
现在如果我创建一个SubClass实例,该对象将不会初始化属性a和 x。
var object = new SubClass;
//object.a == undefined
//object.x == undefined
虽然我理解为什么会发生这种情况,但子类执行超类构造函数初始化的最简洁方法是什么?
首先,该代码中存在大量错误。
这将使IntermediateClass成为SuperClass的姐妹。
IntermediateClass.prototype = SuperClass.prototype;
你永远不需要这样做,构造函数
为你处理。
SubClass.prototype.constructor = SubClass;
也就是说,JavaScript 没有类。继承是基于对象的。你无法做你想要做的事情。
相反,我会在一个单独的函数中提取初始化,然后从子类中调用它。 / p>
一个更好的问题是你想要完成的事情。您正在尝试编写JavaScript,就好像它是Java一样。不是。
Consider the following Javascript snippet,
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;
Now If i create an instance of SubClass, the object will not initialize the property "a" and "x".
var object = new SubClass;
//object.a == undefined
//object.x == undefined
While I understand why this happens, what is the cleanest way for the subclass to perform the initialization done by the super class constructor?
First of all, there's a bunch of errors in that code.
This will make IntermediateClass a sister of SuperClass.
IntermediateClass.prototype = SuperClass.prototype;
You never need to do this, constructor
is handled for you.
SubClass.prototype.constructor = SubClass;
That said, JavaScript doesn't have classes. Inheritance is object-based. You can't do what you're trying to do.
Instead, I would extract the initialisation in a separate function, then call it from the "subclass".
A better question is what you're trying to accomplish. You're trying to write JavaScript as if it was Java. It's not.
这篇关于Javascript - 如果超类构造函数接受参数,如何初始化超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!