浅谈JS的call、apply和bind

前言

call、apply、bind 的作用是改变函数运行时 this 的指向

先搞懂 this,自己初学的时候对 this 是一脸懵逼的 o((⊙﹏⊙))o...

this

总结了一下,this 实际上是在函数被调用时发生的绑定,它指向什么地方完全取决于函数在哪里被调用。但这里有个列外,构造函数的 this 和 es6 的箭头函数的 this 又有所不同。

1.函数调用

 # Window
function print() {
  console.log(this);
}

print(); // 等价于window.print()

2.对象属性调用

谁调用,this 指向谁

const obj = {
  name: 'outside',
  print() {
    console.log(this.name);
  },
  extend: {
    name: 'inside',
    print() {
      console.log(this.name);
    },
  },
};

obj.print(); // outside
obj.extend.print(); // inside

第二个输出这里可能有点难理解,记住谁调用指向谁,是 extend 调用的,指向 extend

3.构造函数

构造函数的 this 将指向 new 出来的对象,在该例子中即 man

我们先看下面的代码:

class Man {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  print() {
    console.log(this.name, this.age);
  }
  extend = {
    name: 'inside',
    age: 99,
    print() {
      console.log(this.name, this.age);
    },
  };
}

const man = new Man('小明', 18);
console.log(man.print()); // 小明 18
console.log(man.extend.print()); // inside 99

第二个输出是不是有点奇怪,是的,我们打印一下 man 对象,发现其跟上一个例子情况是一样的,记住只是构造函数的 this 指向实例对象


4.箭头函数

箭头函数和匿名函数很像,不过箭头函数没有 this,箭头头函数的 this 是继承父执行上下文里面的 this

我们改写一下 3 中的 extend

class Man {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  print() {
    console.log(this.name, this.age);
  }
  extend = {
    name: 'inside',
    age: 99,
    print: () => {
      console.log(this.name, this.age);
    },
    deep_pro: {
      name: 'deep_insise',
      age: 9999,
      print: () => {
        console.log(this); //  Man {extend: {…}, name: "小明", age: 18}
        console.log(this.name, this.age);
      },
    }
  };
}

const man = new Man('小明', 18);
console.log(man.print()); // 小明 18
console.log(man.extend.print()); // 小明 18
console.log(man.extend.deep_pro.print()); // 小明 18

call、apply、bind

上面说了一大堆,搞懂了 this,回到正题

call、apply、bind 的作用是改变函数运行时 this 的指向

  • call、apply 作用是执行一个方法并改变 this,他们的区别是传入参数的方式不同
  • bind 和前面两者不同的是只是返回一个改变了 this 的函数,需手动执行它

call 和 apply 容易混淆问题,我是这么记忆的:call 可以想象为打电话,打电话是一个一个接着打的不可能同时多个,所以 call 是传多个参数,apply 直接一个数组。

调用:

func.call(obj, arg1, arg2, ...);
func.apply(obj, [arg1, arg2, ...]);

我们试着用 call、apply、bind 改变 this:

class Caculate {
  constructor(name) {
    this.name = name;
  }
  add(a, b) {
    return this.name + a + b;
  }
}

const demo = new Caculate('构造函数:');
console.log(demo.add('hello', ' world')); // 构造函数:hello world

1.call

console.log(demo.add.call({ name: 'call改变:' }, 'hello', ' call')); // call改变:hello call

2.apply

console.log(demo.add.apply({ name: 'apply改变:' }, ['hello', ' apply'])); // apply改变:hello apply

3.bind

bind 和 call 一样,参数是一个一个传的

const bind_ = demo.add.bind({ name: 'bind改变:' }, 'hello', ' bind');
console.log(bind_()); // "bind改变:hello bind"

看到这里,相信你已经理解了,上面解释 this 的时候函数调用有两种形式:

print(); // 1.函数调用
man.extend.print(); // 2.对象属性调用

实际上我们可以把它用 call 重写为:

print.call(window);
man.extend.print.call(man.extend);

实现简单的 call、apply、bind

我们也可以动手实现简单的 call、apply、bind,有助于加深理解

call:

Function.prototype.call_ = function (context, ...args) {
  let context_ = context || window;
  // 让 fn 的上下文为 context
  context_.fn = this;
  const result = context_.fn(...args);
  delete context_.fn;
  return result;
};

apply:

Function.prototype.apply_ = function (context, args) {
  let context_ = context || window;
  // 让 fn 的上下文为 context
  context_.fn = this;
  let param_ = args || [];
  const result = context_.fn(param_);
  delete context_.fn;
  return result;
};

bind:

Function.prototype.bind_ = function (context, ...args) {
  let fn = this;
  return function () {
    fn.apply(context, args.concat(...arguments));
  };
};

扩展

上面讲解 this 的时候讲到 this 实际上是在函数被调用时发生的绑定,它指向什么地方完全取决于函数在哪里被调用,但又有特例: 箭头函数和构造函数

其实我们可以用 bind 实现箭头函数,照搬上面的例子:

class Man {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  print() {
    console.log(this.name, this.age);
  }
  extend = {
    name: 'inside',
    age: 99,
    print: function print() {
      console.log(this.name, this.age);
    }.bind(this), // 手动绑定this
  };
}

const man = new Man('小明', 18);
console.log(man.print()); // 小明 18
console.log(man.extend.print()); 小明 18

自己手写一个 new 操作符方法:

function Factory(fn, ...args) {
  const target = Object.create(fn.prototype);
  const res = fn.apply(target, args);
  return res instanceof Object ? res : target;
}

以上纯手敲 + 个人理解,如有不足,欢迎指出~


END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355