In JavaScript, classes are implemented based on their stereotype inheritance mechanism. If two instances inherit properties from the same stereotype object, they are said to be instances of the same class.

Inheritance in ES5

// Create a parent class
function Person(name){
    this.name = name;
    this.className = 'Person';
}
// Is the parent class's prototype mount method
Person.prototype.getName=function(){
    return this.name;
}


// Create a subclass
function Man(name){}// How to inherit Person from Man?
// 1. Initialize the Person class properties in the Man constructor
function Man(name){
    // Bind the attribute of the parent class to Man's this and assign it
    Person.apply(this.arguments);
    Person. Apply (this,arguments); Be sure to write this on the first line to avoid overwriting Man's own attributes
    this.name=name;
}

// 2. Bind the Person prototype
Man.prototype = Object.create(Person.prototype);
// Attach the Person class prototype object to the man. prototype prototype object
// Man = Object.create(Person.prototype);
// If the Man prototype object has its own methods or attributes, they will be overwritten


// 3. Maintain the constructor attribute on the Man prototype
Man.prototype.constructor = Man;
Copy the code

Inheritance in ES6

Es6 introduces class, extends, super, static(part of ES2016 standard)

// Define the parent class
class Person {
    constructor(opt){
        this.name = opt.name;
        this.age = opt.age;
    }
    getName(){
        return this.name;
    }
    // Static methods can also be inherited
    static getAge(){
        return this.age; }}// Define subclasses
class Man extends Person {
    constructor(opt){
        // If there is super, it needs to be executed in the first sentence
        super(opt);
        this.job = 'JS'}}Copy the code