返回

this指向判断:理解this的指向规则

前端






**this的指向判断** 

在JavaScript中,this是一个很重要的概念,它指向当前执行上下文的函数或对象。this的指向可以根据不同的情况而改变,这可能会让一些初学者感到困惑。

本文将介绍this的五种指向判断方法:

1. **函数直接调用** 

当一个函数直接被调用时,this指向调用它的对象。例如:

```javascript
function Person() {
  this.name = "John";
}

var person = new Person();

console.log(person.name); // "John"

在这个例子中,函数Person()直接被调用,this指向调用它的对象person。因此,console.log(person.name)输出"John"。

  1. 函数被别人调用

当一个函数被另一个函数调用时,this指向调用它的函数。例如:

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

function greet() {
  console.log(this.name);
}

person.greet = greet;

person.greet(); // "John"

在这个例子中,函数greet()被函数Person()调用,this指向调用它的函数Person()。因此,console.log(this.name)输出"John"。

  1. new一个实例时

当使用new运算符创建一个实例时,this指向这个实例。例如:

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

var person = new Person();

console.log(person.name); // "John"

在这个例子中,new运算符创建一个Person()实例,this指向这个实例。因此,console.log(person.name)输出"John"。

  1. apply、call、bind时

当使用apply、call、bind方法时,可以显式地指定this指向什么对象。例如:

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

var person = new Person();

var anotherPerson = {};

person.greet.apply(anotherPerson); // "John"

在这个例子中,greet()方法使用apply方法显式地指定this指向anotherPerson对象,因此,console.log(this.name)输出"John"。

  1. 箭头函数中的this

箭头函数中的this与普通函数中的this不同,它总是指向定义它的那个对象。例如:

var person = {
  name: "John",
  greet: () => {
    console.log(this.name);
  }
};

person.greet(); // "John"

在这个例子中,greet()方法是一个箭头函数,它总是指向定义它的那个对象person,因此,console.log(this.name)输出"John"。

setTimeout中的this指向

在setTimeout函数中,this指向window对象。例如:

setTimeout(() => {
  console.log(this.name);
}, 1000);

在这个例子中,setTimeout函数中的回调函数是一个箭头函数,它总是指向定义它的那个对象window,因此,console.log(this.name)输出"undefined"。

如何改变this指向

可以通过使用apply、call、bind方法来改变this指向。例如:

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

var person = new Person();

var anotherPerson = {};

person.greet.call(anotherPerson); // "John"

在这个例子中,greet()方法使用call方法显式地指定this指向anotherPerson对象,因此,console.log(this.name)输出"John"。

结论

this的指向判断是一个很重要的概念,它可以帮助我们理解JavaScript代码是如何执行的。通过本文的介绍,希望大家能够对this的指向判断有更深入的理解。