怎样手写call、apply、bind?

call

Function.prototype.call(this, arg1, arg2, …..)
能够转变this,而且传入参数,马上实行,返回函数返回值

手写call


Function.prototype.myCall = function(context = window, ...args) {
  context = context || window; // 参数默认值并不会消除null,所以从新赋值
  context.fn = this; // this是挪用call的函数
  const result = context.fn(...args);
  delete context.fn; // 实行后删除新增属性
  return result;
}

apply

Function.prototype.apply(this, [arg1, arg2, …..])
能够转变this,而且传入参数,与call差别的是,传入的参数是数组或类数组,马上实行,返回函数返回值

手写apply:

Function.prototype.myApply = function(context = window, args = []) {
  context = context || window; // 参数默认值并不会消除null,所以从新赋值
  context.fn = this; // this是挪用call的函数
  const result = context.fn(...args);
  delete context.fn;
  return result;
}

bind

Function.prototype.bind(this, arg1, arg2, …)
能够绑定this,而且传入参数,体式格局与call雷同,然则不会实行,返回已绑定this的新函数

手写bind:

Function.prototype.myBind = function(context, ...args) {
  const _this = this;
  return function Bind(...newArgs) {
    // 斟酌是不是此函数被继续
    if (this instanceof Bind) {
      return _this.myApply(this, [...args, ...newArgs])
    }
    return _this.myApply(context, [...args, ...newArgs])
  }
}
    原文作者:基尼尔凯
    原文地址: https://segmentfault.com/a/1190000018832498
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞