call、apply以及bind的区别和用法

208 阅读2分钟

call、apply以及bind的区别和用法

1. call、apply、bind的定义?(它们分别是什么?)

call()方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数。

function func(a, b, c) {
  console.log(this.name, a, b, c)
}
const obj1 = { name: 'obj1'}
func.call(obj1, 1, 2, 3) // obj1, 1, 2, 3

apply()方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。

const obj2 = { name: 'obj2' }
func.apply(obj2, [1 ,2, 3]) // obj2, 1, 2, 3

bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将

作为新函数的参数,供调用时使用。

const obj3 = { name: 'obj3' }
const aFunc = func.bind(obj3, 1, 2, 3);
aFunc(); // 要执行一下

2. call、apply、bind的异同?

  • 相同点: 都能改变函数执行时的上下文,将一个对象的方法交给另一个对象执行

  • 不同点: call和apply是立即执行的,调用call和apply的对象,必须是一个函数Function,只是它们在参数上的写法不同。

    bind不是立即执行的,返回值是一个函数,调用后执行。

3. 经典案例

call的使用场景:

  1. 对象的继承
function superClass () {
  this.a = 1;
  this.print = function () {
    console.log(this.a)
  }
}

function subClass () {
  superClass.call(this);
  this.print();
}

subClass();
  1. 借用方法
Array.prototype.slice.call(document.getElementByTagName(*))

apply的使用场景

  1. Math.max
Math.max.call(null, [19, 1, 2])
  1. 实现两个数组的合并
let arr1 = [1, 2, 3];
let arr2 = [4 ,5, 6];

Array.prototype.push.apply(arr1, arr2);
console.log(arr1)

4. 高效记忆小故事

猫吃鱼,狗吃肉,奥特曼打小怪兽。

有天狗想吃鱼了

猫.吃鱼.call(狗,鱼)

狗就吃到鱼了

猫成精了,想打怪兽

奥特曼.打小怪兽.call(猫,小怪兽)

猫也可以打小怪兽了

奥特曼想集成猫狗鱼的能力,生成大招,然后随时使用这个大招

大招 = 集成.bind(奥特曼,猫,狗,鱼)

奥特曼就牛逼了。