call、apply、bind区别

  • call

    • 调用函数并立即执行,逐个传递参数

      function greet(greeting, punctuation) {
      console.log(greeting + ', ' + this.name + punctuation);
      }

      const person = { name: 'Alice' };

      greet.call(person, 'Hello', '!'); // 输出: Hello, Alice!

  • apply

    • 调用函数并立即执行,以数组形式传递参数

      function greet(greeting, punctuation) {
      console.log(greeting + ', ' + this.name + punctuation);
      }

      const person = { name: 'Alice' };

      greet.apply(person, ['Hello', '!']); // 输出: Hello, Alice!

  • bind

    • 返回一个新的函数,不会立即执行,参数可以逐个传递或部分预设

      function greet(greeting, punctuation) {
      console.log(greeting + ', ' + this.name + punctuation);
      }

      const person = { name: 'Alice' };

      const greetAlice = greet.bind(person, 'Hello');
      greetAlice('!'); // 输出: Hello, Alice!