preface

Apply, Call, and bind are the three most commonly used functions to explicitly bind this and are the most popular test points for interviews. Starting with Apply, we’ll walk you through simple versions of the three functions.

By default, you already know the behavior of the above three functions. If you do not know, please check the detailed function description on MDN first.

The realization of the apply

/* * thisArg is the value of this to be used when the function is run * args is an array or array-like object, which is the argument list when the function is called */
Function.prototype.apply = function(thisArg,args){
    /* * When thisArg is undefined or null * defaults to pointing thisArg to window * note that this behavior occurs only in non-strict mode */
    if (typeof thisArg === 'undefined' || thisArg === null){
        thisArg = window;
    }
    // To prevent the original attribute from being overwritten, create a unique value using Symbol
    const fnSymbol = Symbol(a);// Where this refers to the function that calls apply
    thisArg[fnSymbol] = this;
    // Call the function and receive the return value
    constres = thisArg[fnSymbol](... args);// Finally remove the temporary property
    delete thisArg[fnSymbol];
    / / the return value
    return res;
}
Copy the code

The realization of the call

When you implement call, you only need to modify the function declaration. Note that the rest of the ES6 arguments are used. You can also use arguments to implement the call

- Function.prototype.apply = function(thisArg,args)
+ Function.prototype.call = function(thisArg,... args)
Copy the code

The realization of the bind

Bind is a higher-order function that can be implemented using apply. The simplest way to implement bind is shown below.

Function.prototype.bind = function(thisArg) {
    // Method 1: Save the reference to this, which refers to the function that calls bind
    const self = this;
    return function(. args){
        return self.apply(thisArg,args);
    }
    // Use the arrow function directly
    return (. args) = >this.apply(thisArg,args);		
}
Copy the code

Afterword.

In order to facilitate your learning and memory, the above source code as far as possible in the simplest form of presentation, in the real interview, we only need to remember the apply implementation can quickly draw inferno. At the same time, mastering their implementation principle is also the key to grasp this point.

About me

Like to chat, like to share, like the cutting-edge 22 side dish chicken, new to the hope to get your attention. Internships/college recruiting opportunities are even better! Personal public account: Rat son’s front end CodeLife