Three ways to change the direction of this

Time:2022-5-5

Call, apply and bind are the methods to change the direction of this.

Common ground: the first parameter is the pointer to change this. If the first parameter is null / undefined, this points to window by default

Call (countless parameters)

First parameter: change this point
Second parameter: argument
This function will be executed automatically after use

function fn(a,b,c){
        console. log(this,a+b+c); //  This points to window
    }
    fn();
    fn. call(document,1,2,3);// After the call is changed, this points to document  
    //Output #document 6 1, 2 and 3 are arguments, and the results are added to 6

Apply (two parameters)

First parameter: change this point
Second parameter: array (with arguments inside)
Functions are automatically executed when used

function fn(a,b,c){
        console.log(this,a+b+c); 
    }
    fn();
    fn.apply(document,[1,2,3]); 

Bind (countless parameters)

First parameter: change this point
After the second parameter: argument
The return value is a new function
When using, you need to manually call the new function returned under (it will not be executed automatically)

function fn(a,b,c){
    console.log(this,a+b+c); //window
}
let ff = fn. Bind ('xiaoming ', 1,2,3)// Call it manually

The difference between call and apply and bind: the first two can be executed automatically, but bind will not be executed automatically, so it needs to be called manually

The difference between call, bind and apply: the first two have countless parameters, while apply has only two parameters, and the second parameter is an array

Recommended Today

Modify user information changeinfo

When judging the persistence layer: Problem: there is such a problem when modifying user information. For example: the user’s email is not required. It was not empty originally. At this time, the user deletes the mailbox information and submits it. At this time, if it is not empty to judge whether it needs to be […]