Handwritten call, apply, bind functions, and understanding of the implementation principle

Handwritten call, apply, bind functions, and understanding of the implementation principle

If you don’t understand the functions of call, apply and bind, you can read the function and difference of call(), apply() and bind() in the previous article

Handwritten call() function

 	Function.prototype.myCall = function(context, ...args) {
    
    
      context = context || window;
      const fn = Symbol();
      context[fn] = this;
      const result = context[fn](...args);
      delete context[fn];
      return result;
    };
    let a = {
    
     name: "张三" };
    let b = {
    
    
      name: "李四",
      myName: function() {
    
    
        console.log(this.name);
      },
    };
    b.myName.myCall(a); // 打印出"张三",this指向了变量a
1.将myCall函数挂在到Function下,第一个参数就是需要指定的this指向,其余参数利用...args接收。
2.如果没有指定this的指向,默认指向window
3.为当前指定的this指向创建一个唯一的属性,并且将调用myCall的函数赋值给这个唯一值
4.调用这个唯一值,也就是调用当前调用myCall的函数,然后将调用时传入的参数,除context外,其余的全部传入
此时调用了调用myCall的函数,并且将传入的参数传回去, 而调用者已经变成了context,也就是我们指定的this指向
最后将运行结果返回

Handwritten apply() function

    Function.prototype.myApply = function(context, arr) {
    
    
      context = context || window;
      if (!(arr instanceof Array)) {
    
    
        throw new TypeError("It's not a Array");
      }
      const fn = Symbol();
      context[fn] = this;
      const result = context[fn](...arr);
      delete context[fn];
      return result;
    };
    let a = {
    
     name: "张三" };
    let b = {
    
    
      name: "李四",
      myName: function() {
    
    
        console.log(this.name);
      },
    };
    b.myName.apply(a); // 打印出"张三",this指向了变量a
和call()方法区别在于call传参是一个参数列表,而apply方法传参是一个列表数组

Handwritten bind() function

    Function.prototype.myBind = function(context, ...args) {
    
    
      context = context || window
      const that = this
      return () => {
    
    
        that.call(context, ...args);
      }
    };
    let a = {
    
     name_ :"我是a"}
    let b = {
    
     name_ :"我是b",myName:function(){
    
    
      console.log(this.name_);
    }}
    b.myName.myBind(a)()  // 打印出"我是a",this指向了变量a
 1.将myBindl函数挂在到Function下,第一个参数就是需要指定的this指向,其余参数利用...args接收
 2.如果没有指定this的指向,默认指向window
 3.返回一个函数,而后再利用call()函数去改变this指向,以及传递参数
 因为返回的是一个函数,所以可以用new,此处没有对new做出详细解释~

Guess you like

Origin blog.csdn.net/zhengcaocao/article/details/115731680