JavaScript inheritance

The revolution has always been in the hands of the young. The young always inherit the revolution.

Huey Newton. He said that even without knowing how unskilled inheritance make Sub-classes revolt and break super-classes.

As far as I see it, the use of inheritance in JavaScript is the main measure of the JavaScript maturing. Are we still moving around data to support UI, or are we building an application. Here I’ll show three ways to create enheartened objects. All the examples supposed to have the same usage, and return the same results:

let a = new A();
let b = new B();

a.getA() == 'a';
a.getB(); // Uncaught TypeError: a.b1 is not a function

b.getA() == 'a';
b.getB() == 'b';

a.getX() == 'ax';
b.getX() == 'bx';

As simple as can be!

1. Prototype:

function A(){
}


A.prototype.getA = function(){
return 'a';
}
A.prototype.getX = function(){
return 'ax';
}
function B(){
    A.call(this);
}
B.prototype = Object.create(A.prototype)


B.prototype.getB = function(){
    return 'b';
}
B.prototype.getX = function(){
return 'bx';
}

Same approach just with object & spread.

...

B.prototype = {
...A.prototype,
getB: function(){

return 'b';
},
getX: function(){
return 'bx';
}
}
...

2. With property constructor

function A(){
if (!new.target) throw 'A() cannot be invoked without "new"';

this.getA = function(){
return 'a';
}

this.getX = function(){
return 'ax';
}
}
function B(){
if (!new.target) throw 'B() cannot be invoked without "new"';
    A.call(this);
   this.getB = function(){
return 'b';
}

this.getX = function(){
return 'bx';
}
}

3. With ES6 class

class A{
    constructor(){
        
}
   getA(){
       return 'a';
}
getX(){
return 'ax';
}
}

class B extends A{
    constructor(){
        super();
}
   getB(){
       return 'b';
}
getX(){
return 'bx'
}
}