this 指向问题

99 阅读1分钟

在 JavaScript 中,this 关键字表示当前执行上下文的对象。在不同的执行上下文中,this 的值可能会有所不同。

  1. 在全局作用域中,this 指向全局对象,在浏览器中是 window 对象,在 Node.js 中是 global 对象。

  2. 在函数中,this 的值取决于函数被调用的方式。如果函数是作为对象的方法调用,则 this 指向调用方法的对象。例如:

const obj = {
  name: 'John',
  greet: function() {
     console.log(`Hello, ${this.name}!`);
  }
};
obj.greet(); // Output: "Hello, John!"
  1. 如果函数是使用 callapply 方法调用的,则可以使用这些方法的第一个参数来指定 this 的值。例如:
function greet(name) {
  console.log(`Hello, ${name}!`);
} 
greet.call(null, 'John'); // Output: "Hello, John!"
  1. 在箭头函数中,this 的值与定义时的上下文绑定,而不是调用时的上下文。这意味着箭头函数中的 this 总是指向定义时所在的作用域中的 this 值,而不是调用时的 this 值。例如:
const obj = {
  name: 'John',
  greet: () => {
    console.log(`Hello, ${this.name}!`);
  }
}; 
obj.greet(); // Output: "Hello, undefined!"

总结:

全局作用域中或者普通函数中的this指向全局对象window

构造函数中的this指向实例对象,方法里面的this指向这个方法的调用者,即谁调用了这个方法,方法中的this就指向谁。

箭头函数没有自己的this指向,它的this指向上一级作用域中的this