Handwritten call / apply / bind function

Explicit binding for this (arrow functions do not bind this)

1 Implementation of the call function

// 给所有的函数添加一个hycall的方法 原型
Function.prototype.hycall = function(thisArg, ...args) {
    // 在这里可以去执行调用的那个函数(foo)
    // 问题: 得可以获取到是哪一个函数执行了hycall
    // 1.获取需要被执行的函数
    var fn = this;

    // 2.对thisArg转成对象类型(防止它传入的是非对象类型)
    //如果undefined或者null,thisArg=window
    thisArg =
        thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;

    // 3.调用需要被执行的函数
    thisArg.fn = fn;
    var result = thisArg.fn(...args);
    delete thisArg.fn;

    // 4.将最终的结果返回出去
    return result;
};

2 Implementation of the apply function

Function.prototype.hyapply = function(thisArg, argArray) {
    // 1.获取到要执行的函数
    var fn = this;

    // 2.处理绑定的thisArg
    thisArg =
        thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;

    // 3.执行函数
    thisArg.fn = fn;
    var result;
    // if (!argArray) { // argArray是没有值(没有传参数)
    //   result = thisArg.fn()
    // } else { // 有传参数
    //   result = thisArg.fn(...argArray)
    // }

    // argArray = argArray ? argArray: []
    argArray = argArray || [];
    result = thisArg.fn(...argArray);

    delete thisArg.fn;

    // 4.返回结果
    return result;
};

3 Implementation of bind function

Function.prototype.hybind = function(thisArg, ...argArray) {
  // 1.获取到真实需要调用的函数
  var fn = this

  // 2.绑定this
  thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window

  function proxyFn(...args) {
    // 3.将函数放到thisArg中进行调用
    thisArg.fn = fn
    // 特殊: 对两个传入的参数进行合并
    var finalArgs = [...argArray, ...args]
    var result = thisArg.fn(...finalArgs)
    delete thisArg.fn

    // 4.返回结果
    return result
  }

  return proxyFn
}

 4 Differences and comparisons

  • call, apply, and bind are the same : they all change the point of this, and the first parameter passed in is the point of binding this. In non-strict mode, if the first parameter is null or undefined, the global object will be (The browser is window) As the value of this, it should be noted that in strict mode, null is null, and undefined is undefined
  • The only difference between call and apply is : call passes in a parameter list, and apply passes in an array, which can also be a class array
  • The difference between bind, call and apply:  bind returns a function that changes the point of this , which is convenient for calling later, unlike call and apply, which will be called immediately; bind is similar to call, and the parameter list is also passed in, but it can be more Incoming once, no need like call, incoming once
  • It is worth noting : when the function returned by bind uses new as the constructor, the bound this value will be invalid, and this points to the instance object, but the incoming parameters are still valid (the priority of the new call > the bind call)

Guess you like

Origin blog.csdn.net/m0_50789696/article/details/129251879