Prototype-based inheritance
The core of stereotype inheritance is to inherit the attributes of the Parent class in the constructor of the child class via parent.call (this), and then change the stereotype of the child class to new Parent() to inherit the functions of the Parent class.
//ES5 prototype chain constructs objects
/ / parent class
function People(name, age) {
this.name = name || 'pray'
this.age = age || 27
}
// Parent method
People.prototype.sayHi = function () {
console.log(this.name + ' of ' + this.age + ' sayHi')}//ES5 prototype chain inherits objects
/ / subclass
function Student(name, age) {
// Inherits the superclass attributes
People.call(this, name, age)
}
// Inherits the parent method
(function () {
// Create an empty class
let Super = function () {}; Super.prototype = People.prototype;// An instance of the parent class is the prototype of the subclass
Student.prototype = newSuper(); }) ();// Fix the constructor pointing problem
Student.prototype.constructor = Student;
let studentObj = new Student();
studentObj.sayHi()
Copy the code
Class-based inheritance
The core of class implementation inheritance is the use of extends to indicate which parent class it inherits from, and the super inheritance parent properties and methods must be called in the subclass constructor.
// ES6 Class constructs the object
class People {
constructor(name = 'pray', age = 18) {
this.name = name;
this.age = age;
}
sayHi() {
console.log(this.name + ' of ' + this.age + ' says Hi! ')}}//ES6 extends extends from the parent class
class Student extends People {
constructor(name = 'student1', age = '22', score = 90) {
// Inherits the superclass attributes
super(name, age);
// Own attributes
this.score = score;
}
sayHi() {
// Inherit the parent attribute method
super.sayHi()
// own method
console.log('score: + this.score)
}
}
let person = new Student()
person.sayHi()
Copy the code