Implement the call() method

What does Call do?

  1. Set functions as properties of objects;

  2. Specify this to the function and pass in the given arguments to execute the function;

  3. Delete this function after execution;

  4. If no argument is passed, it defaults to window;

    Function.prototype.mycall = (context,… Args) {// Return typeError if (typeof this! == ‘function’) {throw new TypeError(‘ not a function’); }

    context = context || window; context.fn = this; const res = context.fn(... args); delete context.fn; return res;Copy the code

    }

To realize the apply ()

Apply is similar to call

Function.prototype.myapply = (context,args) => { if (typeof this ! == 'function') {throw new TypeError(' not a function'); } context = context || window; context.fn = this; args = args && args[0] || []; const res = context.fn(... args); delete context.fn; return res; }Copy the code

To realize the bind ()

What does bind do?

  1. Return a function, bound to this, passing prefabricated arguments;

  2. Arguments returned by bind can be used as constructors.

    Function.prototype.mybind = (context,… args) => { if (typeof this ! == ‘function’) {throw new TypeError(‘ not a function’); }

    let fn = this; const bind = (... Args2) => {// fn. Apply to keep the context consistent with the bind execution; // this instanceof bind determines whether it is an instanceof bind; Return fn. Apply (this instanceof bind? this : context, [...args,...args2]); } bind.prototype = Object.create(this.prototype); return bind;Copy the code

    }

The bind resolution:

The bind function returns an executable function, so it returns a function at the end. When the function is executed, this should be the same as the object passed in, so you need to use apply.

Bind needs to be able to accept passed arguments and pass them to the target function, and then execute the passed arguments after the previous arguments, so use [… Argus,…argus2] for parameter consolidation;

To bind the object, when performing a new operation after this should refer to the current object, so the fn. Apply the first parameter, make such a judgment this instanceof bind? This: context;

If the function returned by bind changes its prototype, it should not affect fn. Prototype. The two functions should be independent, so use bind.