JavaScript Inheritance and Classes

In many programming languages implemented inheritance. And it also exists in JavaScript. First, consider prototype inheritance.

We describe the function constructor

function Animal(name, weight, color){
 
    this.name = name || 'someAnimal';
    this.weight = weight;
    this.color = color;
 
    //do some actions during initialization
    console.log(this.name + ' construct animal');
}
 
// write the method to the prototype
Animal.prototype.sayName = function(){
    console.log(this.name);
}

We describe the constructor function that inherits the Animal class. And we will expand it, we will add in addition own properties and methods

function Mammal(name, weight, color, limbs){
    Animal.apply(this, arguments);
    this.limbs = limbs || 4;
    console.log(this.name + ' construct mammal');
}
 
Mammal.prototype = Object.create(Animal.prototype);
Mammal.prototype.constructor = Mammal;
 
Mammal.prototype.run = function(){
    console.log('run');
}

Create instances of these classes.

let bird = new Animal('bird', 1, 'black');
let cat = new Mammal('Murzik', 2, 'white', 3);

Check which class cat object belongs to.

console.log(cat instanceof Mammal);// true
console.log(cat instanceof Animal);// true

Now we will do almost the same, just use the syntax of ES6. And also consider the static methods of the class.

class Animal {
 
    constructor(name = 'someAnimal', weight, color){
 
        this.name = name;
        this.weight = weight;
        this.color = color;
 
        // do some actions during initialization
        console.log(this.name + ' construct animal');
    }
 
    sayName(){
        console.log(this.name);
    }
 
    // create the static method
    static getEyes(){
        return 2;
    }
}

We describe a class that inherits Animal and add additional properties and methods

class Mammal extends Animal{
    constructor(name, weight, color, limbs = 4){
 
        // call the parent constructor
        super(name, weight, color);
 
        this.limbs = limbs;
        console.log(this.name + ' construct mammal');
    }
 
    run(){
        console.log('run');
    }
}

Create instances of these classes.

let bird = new Animal('bird', 1, 'black');
let cat = new Mammal('Murzik', 2, 'white', 3);

Check which class cat object belongs to.

console.log(cat instanceof Mammal); //true
console.log(cat instanceof Animal); //true

Call the static getEyes method for the Animal class.

console.log(Animal.getEyes()); //2

As you can see to describe the method does not need to use the word function. And the parent constructor is called by the super keyword. Calling this without calling super() will fail

Comments

Popular posts from this blog

Typical gulpfile.js

Swipe events on touch devices