JavaScript inheritance-borrow constructor inheritance

table of Contents

1. Knowledge review:

 Second, use the constructor to achieve inheritance:

 Three, the problem of borrowing the constructor:


1. Knowledge review:

Before learning new knowledge, let's briefly review the use of call, apply, and bind methods:

The common point of call and apply is that they can change the context of the execution of the function, and hand the method of one object to another object for execution, and it is executed immediately; the bind() method creates a new function, and sets this when calling The key is the value provided.

1. Use of call method:

a: Syntax:

Function.call(obj,[param1[,param2[,…[,paramN]]]])

b: Points to note:

(1) The call method must be a function.

(2) The first parameter of call is an object. The caller of Function will point to this object. If it is not passed, it will default to the global object window.

(3) Starting from the second parameter, any number of parameters can be received. Each parameter will be mapped to the function parameter in the corresponding position. But if all the parameters are passed in as an array, they will be mapped to the first parameter corresponding to Function as a whole, and then the parameters will be empty.

c: Code example:

    var person = {
        fullName:function (city,country) {
            return this.firstName+" "+this.lastName+","+city+","+country;
        }
    };
    var person1 = {
        firstName:"1",
        lastName:"2"
    };
    var person2 = {
        firstName:"3",
        lastName:"4"
    };

    var x = person.fullName.call(person1,"HeNan","China");

    console.log(x);

2. Use of apply method:

a: Syntax:

Function.apply(obj[,argArray])

 b: Points to note:

(1) Its caller must be a function, and it only receives two parameters. The rules of the first parameter are the same as call.

(2) The second parameter must be an array or a class-array, they will be converted into a class-array, passed into the Function, and will be mapped to the corresponding parameter of the Function. This is also a very important difference between call and apply.

c: Code example:

    var person = {
        fullName:function (city,country) {
            return this.firstName+" "+this.lastName+","+city+","+country;
        }
    };
    var person1 = {
        firstName:"1",
        lastName:"2"
    };
    var person2 = {
        firstName:"3",
        lastName:"4"
    };
    
    var y = person.fullName.apply(person2,["HeNan","China"]);
    console.log(y);

 3. Use of bind method: bind()The simplest usage is to create a function so that this function has the same this value no matter how it is called.

a: Syntax:

Function.bind(thisArg[, arg1[, arg2[, ...]]])

b: Points to note:

The return value of the bind method is a function, and needs to be called later before it will be executed

 c: Code:

    function add(a,b){
        console.log(a+b);
    }
    function sub(a,b) {
        console.log(a-b);
    }

    add.bind(sub,5,3)();

 Second, use the constructor to achieve inheritance:

1. In the process of solving the problems caused by the inclusion of reference type values ​​in the prototype, a technique called borrowed constructor (forged object/classic inheritance) was used. The basic idea: call the supertype constructor inside the subtype constructor.

    function SuperType() {
        this.colors = ["red","blue","green"];
    }
    function SubType() {
//        继承了SuperType
        SuperType.call(this);
    }

    var instance1 = new SubType();
    instance1.colors.push("black");
    console.log(instance1.colors);

    var instance2 = new SubType();
    console.log(instance2.colors);

 

 Explanation:

The comments in the code borrow the supertype constructor. By using the call () method (or apply () method), change the point of the function this. We actually called the SuperType constructor in the context of the newly created function SubType instance. In this way, all the object initialization codes defined in the SuperType() function will be executed on the new SubType object. As a result, each instance of SubType will have its own copy of the colors attribute.

2. Borrow the advantages of the constructor: You can pass parameters to the supertype constructor in the subtype constructor.

    function SuperType2(name) {
        this.name = name;
    }

    function SubType2(){
//        继承了SyperType2,同时还传递了参数
        SuperType2.call(this,"萝卜头");
//        实例属性
        this.age = 29;
    }

    var instance2 = new SubType2();

   console.log(instance2.name);
   console.log(instance2.age);

 SuperType2 in the above code only accepts one parameter name, which will be directly assigned to an attribute. When the SuperType2 constructor is called inside the SubType2 constructor, it is actually the name attribute of the SubType2 instance.

 Three, the problem of borrowing the constructor:

It is impossible to avoid the problems of the constructor mode. The methods are defined in the constructor, so there is no way to talk about function reuse. The methods defined in the prototype of the supertype are also invisible to the subtypes. As a result, all types can only use the constructor mode.


Note: Refer to "JavaScript Advanced Programming" for content

Guess you like

Origin blog.csdn.net/weixin_43690348/article/details/112979265