js call 和 bind和apply

184 阅读1分钟

主要区别

在 JavaScript 中,callbind 都是用于改变函数的执行上下文,即改变函数中 this 的值。这两者的主要区别是:

  • call 会立即执行函数
  • bind 会返回一个新的函数,你可以稍后执行这个新函数,而不是立即执行

call的用法

class MyClass {
  constructor() {
    this.value = 'Hello, world!';
  }

  greet() {
    console.log(this.value);
  }
}

const myInstance = new MyClass();
const myOtherInstance = new MyClass();
myOtherInstance.value = 'Hello, OpenAI!';

// 使用 'call' 改变 'greet' 的上下文,将其从 'myInstance' 改变为 'myOtherInstance'
myInstance.greet.call(myOtherInstance); // 输出 'Hello, OpenAI!'

bind的用法 (需要接受一个返回值,返回值为一个新函数)

class MyClass {
  constructor() {
    this.value = 'Hello, world!';
  }

  greet() {
    console.log(this.value);
  }
}

const myInstance = new MyClass();
const myOtherInstance = new MyClass();
myOtherInstance.value = 'Hello, OpenAI!';

// 使用 'bind' 改变 'greet' 的上下文,将其从 'myInstance' 改变为 'myOtherInstance'
const boundGreet = myInstance.greet.bind(myOtherInstance);

boundGreet(); // 输出 'Hello, OpenAI!'

apply的用法(调用需要传参,并且参数存储在一个数组内)

class MyClass {
  constructor() {
    this.value = 'Hello, world!';
  }

  greet() {
    console.log(this.value);
  }
}

const myInstance = new MyClass();
const myOtherInstance = new MyClass();
myOtherInstance.value = 'Hello, OpenAI!';

// 使用 'bind' 改变 'greet' 的上下文,将其从 'myInstance' 改变为 'myOtherInstance'
const boundGreet = myInstance.greet.bind(myOtherInstance);

boundGreet(); // 输出 'Hello, OpenAI!'