js的this指向?

43 阅读2分钟
  • 普通函数 this 指向window
  • 定时器函数 this 指向的是window
  • 立即执行函数 this指向的是window
  • 对象中方法 this指向的是对象
  • 构造函数 this 指向构造函数new出来的实例对象
  • 绑定事件函数 this 指向的是函数的调用者
  • 箭头函数中使用this,this关键字将指向箭头函数定义位置中的this

JavaScript 中的 this 是一个特殊的关键字,它指向当前函数的执行上下文(execution context)。this 的值在函数调用时动态确定,取决于函数的调用方式和上下文。

this 的指向有以下几种情况:

  1. 默认绑定:如果函数是独立调用的,即没有通过对象或上下文来调用,那么 this 将指向全局对象(在浏览器中是 window 对象,在 Node.js 中是 global 对象)。
  2. 隐式绑定:如果函数作为对象的方法调用,那么 this 将指向调用该方法的对象。
  3. 显式绑定:通过 callapplybind 方法,可以显式地指定函数执行时的 this 值。
  4. new 绑定:当使用 new 关键字创建对象时,this 将指向新创建的对象。
  5. 箭头函数:箭头函数没有自己的 this 绑定,它会继承外部作用域的 this 值。

需要注意的是,箭头函数的 this 值在定义时确定,并且无法通过 callapplybind 方法来改变。它会继承外部作用域的 this 值。

在使用 this 时,需要注意上下文的绑定,以确保它指向预期的对象。不同的函数调用方式和上下文会导致 this 的不同指向,因此在编写 JavaScript 代码时,我们需要了解 this 的工作原理,以避免出现意外的结果。

// 默认绑定
function sayHello() {
  console.log(this);
}

sayHello(); // Output: Window (浏览器中的全局对象) 或 Global (Node.js中的全局对象)

// 隐式绑定
const obj = {
  name: 'John',
  sayName: function() {
    console.log(this.name);
  }
};

obj.sayName(); // Output: John

// 显式绑定
function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = {
  name: 'Alice'
};

greet.call(person); // Output: Hello, Alice

// new绑定
function Person(name) {
  this.name = name;
}

const john = new Person('John');
console.log(john.name); // Output: John

// 箭头函数
const obj = {
  name: 'Alice',
  sayName: () => {
    console.log(this.name);
  }
};

obj.sayName(); // Output: undefined