JS Inheritance method is mainly 2 kinds, one is through the prototype way, one is by borrowing the Call&apply constructor method.
1. Prototype (prototype):
function Body (name,age) {//Create a body class
this.name = name;//give the underlying property name, age
this.age = age;
}
Body.prototype.sayName =function () {//To define a Sayname method for the prototype
Console.log (this.name);
}
var a = new body (' Wutao ', ' 10 ');//Create a Body instance object
function Another () {}
Another.prototype = new Body (' www '); The body instance object is given to the prototype property of the newly created subclass (Another), so that Another has the body's properties and methods
var b = new Another ();//Create Instance
of the Another subclass Another.prototype.sex = "Mail"; properties and methods for defining subclasses
Another.prototype.saySex = function () {
console.log (this.sex) ;
}
A.sayname ();//wutao
b.sayname (); instance B has the parent body method Sayname
b.saysex ();//mail Instance B has its own defined method Saysex
2. Borrow constructor (call&apply), also can be understood as modular inheritance
call :
function person (name) {
this.name = name;
This.sayhello = function () {
console.log (this.name);
}
}
function Son (name,age) {
person.call (this,name,age);//call usage: Point the this pointer to the parent class constructor, and then pass in the argument so that it has the properties and methods
of the parent class This.age = age;
This.sayfunc = function () {
Console.log (this.name+ "-" +this.age);
}
}
var a = new person (' Wutao ');
var B = new Son ("wwwwww");
A.sayhello ();//wutao
B.sayhello ();//wwwwww; method of the parent person inherited by call SayHello
B.sayfunc ();//wwwwww-22
Apply
function person (name) {
this.name = name;
This.sayhello = function () {
console.log (this.name);
}
}
function Son (name,age) {
person.apply (this,[name,age]);//apply usage: Like call, point the this pointer to the parent class constructor and pass in an array argument consisting of parameters, Attributes and methods that have the parent class
this.age = age;
This.sayfunc = function () {
Console.log (this.name+ "-" +this.age);
}
}
var a = new person (' Wutao ');
var B = new Son ("TTT", 222);
A.sayhello ();//wutao
B.sayhello ();//ttt; The method of the parent person that is inherited by apply SayHello b.sayfunc
();//ttt-222
JS the main inheritance method on these 2 kinds, there are, of course, several ways to inherit, but some inheritance means that modifying instance methods and properties directly modifies the methods and properties of the stereotype after the instance is created, which is less meaningful unless the business has similar requirements.
The above is about JavaScript inheritance way of detailed introduction, I hope to help you learn.