Native JS implements call, apply, bind methods (detailed explanation)

Summary

We know that if we want to change the direction of this, we have three ways to do it.
call and apply are direct calls, while bind returns a method and will not be called directly.

If we want to understand it deeper, then we can implement it ourselves.

First of all, let's think about it, the caller of these three methods is a method, any method.

Since this is the case, all methods can call these three methods again, so the three methods we wrote must be written under the prototype of Function.

With this idea, we can implement:

call method

First, let's review how the call method is called:

let p1 = {
    
    
  name: 'lisi'
}

let a = function (arg1, arg2) {
    
    
  console.log(arg1, arg2);
  console.log(this.name);
}

a.call(p1, 'aa', 'bb');

We can see that among the parameters passed in by the call method, the first is the changed this pointing to the object, and the rest are the parameters of the original method.


So the call method we wrote ourselves is to process arguments, but arguments is an iterable object, so it will be more convenient if we convert it into an array first.

Here we use the Array.from() method to convert the arguments.


So how do we change the direction of this in the call method?
In fact, it is very simple, because we can get the object of p1, we only need to add a method under p1 , copy the original method, and call it directly .


In another case, if the original function has a return value, we also need to deal with it.

That is, when calling the new method directly, use a variable to receive and return .

Function.prototype.mycall = function () {
    
    
  let arr = Array.from(arguments)
  let newThis = arr.shift();
  newThis.fun = this;
  let result = newThis.fun(...arr);
  return result
}

apply method

Let's review the use of the apply method:

a.apply(p1, ['aa', 'bb'])

As you can see, the second parameter of the apply method is an array, so we don't need to convert the arguments into an array.

So we can write directly according to the call method

Function.prototype.myapply = function () {
    
    
  let newThis = arguments[0];
  let arr = arguments[1];
  newThis.fun = this;
  let result = newThis.fun(...arr);
  return result
}

bind method

Let's take a look at how to use the bind method first.

let x = a.bind(p1, 'aa', 'bb');
x();

That is to say, normally speaking, compared with the call method, our bind method does not call directly and returns a new method

So we actually only need to put the method directly called in the call into a function and return the function .

Function.prototype.mybind = function () {
    
    
  let arr = Array.from(arguments)
  let newThis = arr.shift();
  newThis.fun = this;
  return function () {
    
    
    newThis.fun(...arr)
  }
}

Guess you like

Origin blog.csdn.net/weixin_46726346/article/details/119749272