Javascript - how to initialize super class if super class constructor takes arguments

点点圈 提交于 2019-12-10 18:16:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!