Today I learned a bit of JS inheritance, JS in the inheritance of the main four kinds, prototype inheritance, constructor inheritance, call/apply inheritance and es6 inheritance of extend.
1. Prototype Inheritance:
Prototype inheritance mainly uses the prototype of the JS object to refer to the parent class's constructor to copy the parent class's methods.
//define a person class functionPerson (name) { This. name=name; } //Greetingperson.prototype.sayhello=function() {alert ("Hello,my name is" + This. Name); } //defining the Man class, inheriting the person class functionMan (name,age) { This. name=name; This. age=Age ; } Man.prototype=NewPerson (); varman=NewMan ("The Old King next Door", 30); Man.sayhello ();
2. Constructor inheritance
The constructor of the parent class is called in the subclass to complete the inheritance.
//define a person class functionPerson (name) { This. name=name; This. sayhello=function() {alert ("Hello,my name is" + This. Name); } } //defining the Man class, inheriting the person class functionMan (name,age) { This. constructor=Person ; This. Constructor (name); This. age=Age ; } varman=NewMan ("The Old King next Door", 30); Man.sayhello ();
3.call/apply inheritance
Using the Call/apply method to invoke the parent class constructor to implement inheritance
//define a person class functionPerson (name) { This. name=name; This. sayhello=function() {alert ("Hello,my name is" + This. Name); } } //defining the Man class, inheriting the person class functionMan (name,age) {Person.call ( This, name); This. age=Age ; } varman=NewMan ("The Old King next Door", 30); Man.sayhello ();
4.extends inheritance
Use ES6 to define the method of the class, similar to the way Java defines the class to implement inheritance, note that some browsers are incompatible--
' Use strict '; //define a person classclass person{//constructor FunctionConstructor (name) { This. name=name; } SayHello () {alert ("My name is" + This. Name); }} class Man extends person{constructor (name,age) {//calling the parent class constructorsuper (name); This. age=Age ; } } varman=NewMan ("The Old King next Door", 30); Man.sayhello ();
Summary of several ways to inherit JS object