javascriptprototype-programmingprototype-oriented

How do you do inheritance in JavaScript without sharing the same instance of the super class between all instances of the sub class?


I noticed that every tutorial on how to do JavaScript inheritance does this:

SubClass.prototype = new SuperClass();

But this will create a single instance of the super class and share it among all the instances of the sub class.

The problem is that I would like to pass arguments to the super class constructor which originate from arguments passed to the sub class.

In Java this would be done like this:

class SubClass extends SuperClass {
  public SubClass(String s) {
    super(s);
  }
}

I tried doing something like this:

function SubClass(args) {
  this.constructor.prototype = new SuperClass(args);
}

But this will not work. So is there a way to do this in JavaScript?


Solution

  • This is how I have always done it.

    // Parent object
    function Thing(options)
    { 
        //do stuff
    }
    
    Thing.prototype.someMethod = function(){
        // some stuff
       console.log('hello');
    }
    
    // child object which inherits from the parent
    function OtherThing(options)
    {       
        Thing.call(this, options);
        // do stuff for otherthing
    }
    
    OtherThing.prototype = new Thing();
    
    OtherThing.prototype.someMethod = function(){
       // call things original function
       Thing.prototype.someMethod.call(this);
    
       // now do anything different
       console.log('other thing says hi');
    }
    
    
    var testObj = new OtherThing();
        testObj.someMethod();
    

    Live Demo