改变 this 的指向:call、apply、bind

1. 使用 call 方法

call 方法可以显式地调用一个函数,并指定 this 的指向

function greet(greeting) {
  console.log(`${greeting}, my name is ${this.name}`);
}

const person = { name: 'Alice' };

greet.call(person, 'Hello'); // 输出: "Hello, my name is Alice"

特点:

  • call 的第一个参数是要指定的 this

  • 后续的参数是函数的参数,逐个传递。


2. 使用 apply 方法

applycall 类似,只是传递函数参数的方式不同,apply 使用数组传递参数。

function greet(greeting, punctuation) {
  console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

const person = { name: 'Bob' };

greet.apply(person, ['Hi', '!']); // 输出: "Hi, my name is Bob!"

特点:

  • 第一个参数是要指定的 this

  • 第二个参数是一个参数数组。


3. 使用 bind 方法

bind 方法不会立即调用函数,而是返回一个新的函数,this 指向被永久绑定。

function greet(greeting) {
  console.log(`${greeting}, my name is ${this.name}`);
}

const person = { name: 'Charlie' };

const boundGreet = greet.bind(person);
boundGreet('Hello'); // 输出: "Hello, my name is Charlie"

特点:

  • 不会立即调用函数,而是返回一个新函数。

  • 绑定后的函数可以多次使用,this 指向不会改变。


4. 在箭头函数中

箭头函数中的 this 是在定义时绑定的,而不是调用时绑定。它继承自定义它时所在的作用域。

const person = {
  name: 'Diana',
  greet: function () {
    const innerArrow = () => {
      console.log(`Hello, my name is ${this.name}`);
    };
    innerArrow();
  },
};

person.greet(); // 输出: "Hello, my name is Diana"

特点:

  • 箭头函数没有自己的 this,会捕获定义时的 this

  • 常用于回调函数中避免丢失 this


5. 在构造函数或类中通过 selfthat 变量

在某些情况下(如传统函数回调),可以通过保存 this 的引用来改变指向。

function Person(name) {
  this.name = name;

  const self = this; // 保存当前的 this
  setTimeout(function () {
    console.log(`Hello, my name is ${self.name}`);
  }, 1000);
}

const person = new Person('Eve'); // 输出: "Hello, my name is Eve"

特点:

  • 手动保存 this,适合 ES6 之前的语法环境。

  • 现代代码中推荐使用箭头函数替代。


6. 直接改变函数上下文(this

在事件处理器中,可以显式设置 this

const button = document.querySelector('button');

button.addEventListener('click', function () {
  console.log(this); // this 指向 button
});

// 使用 bind 改变 this 指向
button.addEventListener('click', function () {
  console.log(this.name);
}.bind({ name: 'Button Object' }));

总结表

方法 描述 是否立即调用
call 显式调用函数并指定 this
apply 显式调用函数并指定 this,参数以数组形式传递
bind 创建一个新函数,this 指向绑定的对象
箭头函数 自动绑定定义时的 this
手动保存 this 保存当前作用域的 this 到变量中
posted @ 2025-06-12 19:12  SimoonJia  阅读(24)  评论(0)    收藏  举报