MST

星途 面试题库

面试题:JavaScript中bind、call与apply方法的区别

请详细阐述JavaScript中bind、call与apply方法在使用方式和功能特性上的区别,并举例说明如何利用这些方法改变函数执行时的this指向。
34.8万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

1. 使用方式区别

  • callfunc.call(thisArg, arg1, arg2, ...)thisArg为函数执行时this指向的对象,后续参数arg1, arg2, ...为传递给函数的参数,按顺序依次列出。
  • applyfunc.apply(thisArg, [arg1, arg2, ...])thisArg同样是函数执行时this指向的对象,但第二个参数是一个数组,该数组包含要传递给函数的所有参数。
  • bindfunc.bind(thisArg, arg1, arg2, ...)thisArg是函数执行时this指向的对象,后续参数arg1, arg2, ...为传递给函数的参数。bind方法返回一个新函数,不会立即执行原函数。

2. 功能特性区别

  • callapply:这两个方法都会立即执行调用它们的函数,并将函数中的this指向thisArg。它们的主要区别仅在于传递参数的形式。
  • bindbind方法返回一个新的函数,这个新函数的this被绑定到thisArg,并且可以预先传入部分参数。新函数在调用时,this始终指向bind方法中指定的thisArg,不会被其他方式改变。

3. 改变this指向示例

// 定义一个对象
const person = {
  name: 'John',
  age: 30,
  sayHello: function() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
};

// 定义另一个对象
const anotherPerson = {
  name: 'Jane',
  age: 25
};

// 使用 call 改变 this 指向
person.sayHello.call(anotherPerson); 
// 输出: Hello, my name is Jane and I'm 25 years old.

// 使用 apply 改变 this 指向
person.sayHello.apply(anotherPerson); 
// 输出: Hello, my name is Jane and I'm 25 years old.

// 使用 bind 改变 this 指向
const newFunction = person.sayHello.bind(anotherPerson);
newFunction(); 
// 输出: Hello, my name is Jane and I'm 25 years old.
// 带参数函数示例
const add = function(a, b) {
  return this.value + a + b;
};

const obj = { value: 1 };

// call 传递参数
const resultCall = add.call(obj, 2, 3); 
console.log(resultCall); 
// 输出: 6

// apply 传递参数
const resultApply = add.apply(obj, [2, 3]); 
console.log(resultApply); 
// 输出: 6

// bind 传递参数
const newAdd = add.bind(obj, 2);
const resultBind = newAdd(3); 
console.log(resultBind); 
// 输出: 6