问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/7844843/javascript-how-to-initialize-super-class-if-super-class-constructor-takes-argu