Skip to content Skip to sidebar Skip to footer

Javascript - How To Initialize Super Class If Super Class Constructor Takes Arguments

Consider the following Javascript snippet, var SuperClass = function(x){ this.x = x; this.a = 5; }; var SubClass = function(x){ } function IntermediateClass(){}; Intermed

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

Post a Comment for "Javascript - How To Initialize Super Class If Super Class Constructor Takes Arguments"