返回

用范例解释JS中的this指向问题

前端

JavaScript中的this指向问题一直是很多初学者的痛点,今天就让我们用范例来说一说this指向问题。

全局环境

当this出现在全局环境下的函数中,this指向宿主环境(浏览器下是window对象)。

function greet() {
  console.log(this); // 输出:window
}

greet();

函数调用

当this出现在函数调用中,this指向函数调用时的上下文对象。

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

person.greet();

对象方法

当this出现在对象方法中,this指向调用该方法的对象。

const person = {
  name: 'John',
  greet: function() {
    console.log(this.name); // 输出:John
  }
};

person.greet();

构造函数

当this出现在构造函数中,this指向新创建的对象。

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

const person = new Person('John');

console.log(person.name); // 输出:John

箭头函数

箭头函数没有自己的this,而是继承外层函数的this。

const person = {
  name: 'John',
  greet: () => {
    console.log(this.name); // 输出:undefined
  }
};

person.greet();

事件处理

在事件处理函数中,this指向触发事件的元素。

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

button.addEventListener('click', function() {
  console.log(this); // 输出:button元素
});

bind, call, apply

bind、call、apply都可以改变函数的this指向。

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

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

button.addEventListener('click', person.greet.bind(person));

以上只是JavaScript中this指向问题的一些常见场景,希望对大家理解this指向有所帮助。