返回

函数中this对象的详解

前端

一、this的绑定

this并不是在编写的时候绑定的,而是在运行时绑定的。它的上下文取决于函数调用时的各种条件。

二、this的指向

1. 函数调用

当一个函数被直接调用时,this指向全局对象,即window对象。

function sayHello() {
  console.log(this); // window
}

sayHello();

2. 方法调用

当一个函数作为对象的属性被调用时,this指向该对象。

const person = {
  name: 'John',
  sayHello() {
    console.log(this); // person
  }
};

person.sayHello();

3. 构造函数调用

当一个函数被用作构造函数时,this指向新创建的对象。

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

const person = new Person('John');

console.log(person); // Person { name: 'John' }

4. 回调函数

当一个函数作为回调函数被调用时,this指向调用它的对象。

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

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

三、严格模式下的this

在严格模式下,如果一个函数没有绑定到任何对象,那么this将指向undefined。

"use strict";

function sayHello() {
  console.log(this); // undefined
}

sayHello();

四、非严格模式下的this

在非严格模式下,如果一个函数没有绑定到任何对象,那么this将指向window对象。

function sayHello() {
  console.log(this); // window
}

sayHello();

五、总结

this是JavaScript中一个非常重要的概念,它表示当前执行上下文中的对象。在函数中,this指向当前正在执行的函数所属的对象,在严格模式下,如果函数没有绑定到任何对象,那么this将指向undefined,在非严格模式下,this将指向window对象。