How to implement call, apply and bind in native js

How to implement call, apply and bind in native js

1. Implement call

step:

  1. Set the function as a property of the object;
  2. Assign this to the function and pass in the given parameters to execute the function;
  3. Delete this function after execution;
  4. If no parameters are passed in, the default is to point to window;
Function.prototype.mycall = function (context, ...args) {
    //Judge whether it is a function. If it is not a function, an error will be reported if (typeof this !== "function") {
        throw new Error("not a function");
    }
    context = context || window;
    context.fn = this;
    const res = context.fn(...args);
    delete context.fn;
    return res;
}

Test code:

var name = "Li Hui", age = 25;
var obj = {
    name: "Zhou Guo",
    objAge: this.age,
    myFun: function (fm, to) {
        console.log(`name: ${this.name}, age: ${this.age}, from: ${fm}, to: ${to}`)
    }
};
var person = {
    name: "younger brother",
    age: 12,
};

Function.prototype.mycall = function (context, ...args) {
    //Judge whether it is a function. If it is not a function, an error will be reported if (typeof this !== "function") {
        throw new Error("not a function");
    }
    context = context || window;
    context.fn = this;
    const res = context.fn(...args);
    delete context.fn;
    return res;
}

obj.myFun.mycall(person, "Chengdu", "Renshou"); //Name: younger brother, age: 12, from: Chengdu, to: Renshou

2. Implement apply

Function.prototype.myApply = function (context, ...args) {
    //Judge whether it is a function. If it is not a function, an error will be reported if (typeof this !== "function") {
        throw new Error("not a function");
    }
    context = context || window;
    context.fn = this;
    args = args && args[0] || [];
    const result = context.fn(...args);
    delete context.fn;
    return result;
}

Test code:

obj.myFun.myApply(person, ["Chengdu", "Renshou"]); //Name: younger brother, age: 12, from: Chengdu, to: Renshou

3. Implement bind

The bind() method mainly binds a function to an object. bind() will create a function, and the value of the this object in the function body will be bound to the value of the first parameter passed into bind().

Method 1: Using apply

Function.prototype.myBind = function () {
    let self = this; //Save the original function let context = [].shift.call(arguments); //Save the this context that needs to be bound let args = [...arguments]; //Convert the remaining parameters passed in to an array return function () { //Return a new function self.apply(context,[].concat.call(args,[...arguments]));
    }
}

ES6 simplifies it:

Function.prototype.myBind = function (context, ...args1) {
        return (...args2) => { //Return arrow function, this is bound to the function object that calls this method context = context || window;
            return this.apply(context, args1.concat(args2));//Merge parameters}
    }

Method 2: Not using call and apply

Combine the above code with the js handwritten apply code:

Function.prototype.myBind = function (context, ...args1) {
    return (...args2) => { //Return arrow function, this is bound to the function object that calls this method context = context || window;
        context.fn = this;
        const args = args1.concat(args2);
        const res = context.fn(...args);
        delete context.fn;
        return res;
    }
}

Test code:

obj.myFun.myBind(person, "Chengdu", "Renshou")(); //Name: younger brother, age: 12, from: Chengdu, to: Renshou

The above is the details of how native js implements call, apply and bind. For more information about js implementation of call, apply and bind, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Example code for using JS to simply implement the apply, call and bind methods
  • Detailed explanation of the implementation principles of call, apply, and bind in JavaScript
  • How to implement a simple version of call, apply, bind using 50 lines of javascript code
  • Detailed explanation of the code for implementing call, bind, and apply in Javascript

<<:  How to reset MySQL root password under Windows

>>:  How to use tcpdump to capture packets in Linux system

Recommend

MySQL 8.0.20 installation and configuration tutorial under Docker

Docker installs MySQL version 8.0.20 for your ref...

How to implement remote access control in Centos 7.4

1. SSH remote management SSH is a secure channel ...

Introduction to common MySQL storage engines and parameter setting and tuning

MyISAM, a commonly used storage engine in MySQL c...

Eight hook functions in the Vue life cycle camera

Table of contents 1. beforeCreate and created fun...

18 common commands in MySQL command line

In daily website maintenance and management, a lo...

Implementation steps for building FastDFS file server in Linux

Table of contents 1. Software Package 2. Install ...

Docker cleaning killer/Docker overlay file takes up too much disk space

[Looking at all the migration files on the Intern...

Use tomcat to deploy SpringBoot war package in centos environment

Prepare war package 1. Prepare the existing Sprin...

mysql subquery and join table details

Table of contents 1. What is a subquery? 2. Self-...

CSS multi-column layout solution

1. Fixed width + adaptive Expected effect: fixed ...

What you need to know about responsive design

Responsive design is to perform corresponding ope...

Web page production TD can also overflow hidden display

Perhaps when I name this article like this, someon...