OOP inheritance

Inheritance: The essence of inheritance is the prototype chain.

Implementations inherit in several ways:

1. Constructor inheritance:

function Parent1(){
    this.name = 'parent1';
}                                                                                                                                                                                                                                                                                                                                       Parent1.prototype.say = function(){ console.log('Parent1-say!')}
function Child1(){
    Parent1.call( this ); //call and apply methods are both used to transfer the context (change the pointer of this), so that the this of the function calling the call method points to its parameter (that is, this here ), so Child1 has name attribute, and its value is 'parent1'.
    this.sex = 'man'; The functions of call and apply are exactly the same, except that their second parameter is different. The parameters of call must be listed one by one, and the parameter of apply is an array, which can also be replaced by arguments.
}
var p1 = new Child1 ();

     The disadvantage of this approach is that the parent class prototype chain cannot be inherited.

    When we add properties or methods to Parent1.prototype it will not be inherited by Child1.

2. Prototype chain inheritance:

function P1() {
    this.name = 'parent1';
    this.friends = [1, 2, 3];
}
C1.prototype= new P1; If you don't pass parameters, you can don't write '()'
function C1() {
    this.sex = 'man';
}
var a1 = new C1, a2 = new C1;
console.log(a1, a2);
a1.friends.push(4);

    We just added 4 to the friends property of the a1 instance object in the last line, but the printed friends of a2 also have this 4, because their prototype objects all point to the same instance object of P1. Then this does not satisfy the idea that each instance is independent.

Combination inheritance:

function P1() {
    this.name = 'parent1';
    this.friends = [1, 2, 3];
}
C1.prototype= new P1;
function C1() {
    P1.call(this);
    this.sex = 'man';
}
var a1 = new C1, a2 = new C1;
console.log(a1, a2);
a1.friends.push(4);

    Although this method realizes the isolation between each instance, the constructor P1 is executed twice.

Optimizing inheritance:

function P1() {
    this.name = 'parent1';
    this.friends = [1, 2, 3];
}
C1.prototype= P1.prototype;
C1.prototype.constructor = C1;
function C1() {
    P1.call(this);
    this.sex = 'man';
}
var a1 = new C1, a2 = new C1;
console.log(a1, a2);
a1.friends.push(4);

This method is the most optimized inheritance method. Not only inherits the prototype chain of the parent class, but also defines its own constructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325590925&siteId=291194637