Implement new, apply, call, bind

new method

  • Create a new object and its implicit point Prototype constructor prototype __proto__
  • The constructor is executed to modify this point
  • Return the object
function myNew(fun){
    return (...args)=>{
        let obj = {
            __proto__:fun.prototype
        };
        fun.call(obj,...args);
        return obj; 
    }
}

apply

  • To modify this method will function bound to the incoming object and perform the functions bound,

core content

// 为了让所有函数都有该方法,所以需要绑定到Function的原型上
Function.prototype.myApply = function(context){
    context.fn = this; // 为了让函数中的this指向传入的对象,需要让对象来调用该方法
    context.fn(...arguments[1])
    return res;   
}

Full implementation of

Function.prototype.myApply = function(context){
    // 判断调用者是否为函数
    if(typeof this !=='function'){
        throw new TypeError('not function')
    }

    context = context || window;
    context.fn = this; // 为了让函数中的this指向传入的对象,需要让对象来调用该方法
    let res = null;
    if(arguments[1]){
        res = context.fn(...arguments[1])
    }else{
        res = context.fn();
    }
    //  删除绑定
    delete context.fn;
    return res;   
}

call

  • And apply the difference parameter passing is not the same, apply the second parameter is an array, call transfer method is one of

core content

// 将方法挂载到目标上执行并返回
Function.prototype.mycall = function(context){
    console.log(arguments); // {0:{name:bonly},1:1,2:2}
    console.log(...arguments); // { name: 'bonly' } 1 2 3
    console.log([...arguments].slice(1)); // [1,2,3]
    let args = [...arguments].slice(1);
    context.fn = this;
    context.fn(...args);
}

full version

// 思路:将要改变this指向的方法挂到目标this上执行并返回
Function.prototype.mycall = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('not funciton')
  }
  context = context || window
  context.fn = this
  let arg = [...arguments].slice(1)
  let result = context.fn(...arg)
  delete context.fn
  return result
} 

bind

  • With the call and apply only difference is that this refers to modifications, and returns to awaiting execution function

core content

Function.prototype.myBind = function(context){
    context.fn = this;
    return () => {
        let args = [...arguments].slice(1);
        context.fn(...args);
    }
}

full version

// 思路:类似call,但返回的是函数
Function.prototype.mybind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  let _this = this
  let arg = [...arguments].slice(1)
  return function F() {
    // 处理函数使用new的情况
    if (this instanceof F) {
      return new _this(...arg, ...arguments)
    } else {
      return _this.apply(context, arg.concat(...arguments))
    }
  }
}

Guess you like

Origin www.cnblogs.com/bonly-ge/p/12067251.html