Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS inheritance with/without using prototype

I am trying to learn inheritance. If I am defining my method superPrint() in SuperClass, I am unable to execute using the child instance

eg: new ChildClass().superPrint(); //Throws error fn not available

/*Parent Class*/
var SuperClass= function(){
  this.name = '';
  this.superPrint = function(){console.log('Doesnt Work');};
}

/*Child Class*/
var ChildClass= function(){
    this.print=function(){
        console.log('Always works');
    }
}

/*Child method inheriting from the parent method*/
ChildClass.prototype = Object.create(SuperClass.prototype);

/*Instantiating the child method*/ 
var obj = new ChildClass();
obj.print();//This works
obj.superPrint();//This gives error *******

But if the function superPrint() is defined using prototype it works. Why? (called using new ChildClass().workingPrint(); now it will work)

/*Parent Class*/
var SuperClass= function(){
   this.name = '';
}

SuperClass.prototype.workingPrint = function(){console.log('This Works');};
like image 543
joyBlanks Avatar asked Sep 16 '26 09:09

joyBlanks


1 Answers

this.superPrint is a method on the instances SuperClass will create. Since you only copy the prototype over into ChildClass and not create a SuperClass instance for your ChildClass, it won't contain the instance methods.

If you want to use object.create, you could add something like SuperClass.call(this); to the definition of your ChildClass, in addition to copying the prototype.

like image 112
Shilly Avatar answered Sep 17 '26 23:09

Shilly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!