• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

How to use js to implement a function.prototype. call to modify this in Function?

Basic concepts of Call

Note: The syntax and actions of this method are similar to those of apply(), except that call() accepts a list of arguments, while apply() accepts an array of arguments.

The basic usage of call

function zz(name) { console.log(this); console.log(name, this.name) }; let a = { name: 234 } zz.call(a, ["abc", "2332"]); // Print values {name, 234}, // [" ABC ", "2332"], 234 zz(); // I am underpaidCopy the code

Write a call

Function.prototype.myCall = function(context,... args){ let cxt = context || window; Let func = Symbol() CXT [func] = this; let func = Symbol() CXT [func] = this; let func = Symbol() CXT [func] = this; args = args ? Args: [] // Call func in the form of an object call, in which this refers to CXT, which is passed in to bind this to const res = args. Length > 0? cxt[func](... args) : cxt[func](); // delete this method, otherwise it will pollute the incoming object (add this method) delete CXT [func]; return res; }Copy the code

The basic concepts of Apply

The call() method is similar to apply() except that call() takes a list of parameters, while apply() takes an array of parameters.

Apply the usage of the

function zz(name, age) {
    console.log(this);
    console.log(name,age, this.name)
};
let a = {
    name: 234
}
zz.apply(a, ["abc", "2332"]);
Copy the code

Common cases for Apply

const arr = [10, 16, 23, 6, 16]; const max = Math.max.apply(Math, arr); // 23 const min = Math.min.apply(Math, arr); / / 6Copy the code

Handwritten apply

Function.prototype.myApply = function(context,args = []){ let cxt = context || window; Let func = Symbol() CXT [func] = this; let func = Symbol() CXT [func] = this; let func = Symbol() CXT [func] = this; // Call func as an object call, in which case this refers to CXT, which is passed in to bind this to const res = args.length > 0? cxt[func](... args) : cxt[func](); delete cxt[func]; return res; }Copy the code

Basic concepts of BIND

The basic use of bind

const module = { x: 42, getX: function() { return this.x; }}; const unboundGetX = module.getX; console.log(unboundGetX()); // The function gets invoked at the global scope // expected output: undefined const boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // expected output: 42Copy the code

The realization of the bind

Function.prototype.myBind = function (context, ... Const fn = this, const fn = this, const fn = this, const fn = this, const fn = this [] args = args? Args: [] // returns a newFn function in which newFn(... newFnArgs) { if (this instanceof newFn) { return new fn(... args, ... newFnArgs) } return fn.apply(context, [...args,...newFnArgs]) } }Copy the code