返回
从 ECMAScript 角度深度剖析 this 指向
前端
2023-12-23 07:33:07
前言
本文参考 ECMAScript 规范,结合各路大神的博客,深入剖析 this 指向的原理。本文从 ECMAScript 的角度出发,旨在帮助读者更深入地理解 this 指向。本文将从题目切入,通过不同方法调用函数时 this 指向发生的变化来加深对 this 指向的理解。
this 指向的本质
在 JavaScript 中,this 指向当前执行代码的作用域对象。作用域对象可以是全局对象、函数对象、构造函数对象或类实例对象。
this 指向是如何确定的
this 指向的确定取决于函数的调用方式。函数调用方式主要有以下几种:
- 函数作为普通函数调用
- 函数作为构造函数调用
- 函数作为方法调用
- 函数作为箭头函数调用
函数作为普通函数调用
当函数作为普通函数调用时,this 指向全局对象。
function foo() {
console.log(this);
}
foo(); // 输出: Window
函数作为构造函数调用
当函数作为构造函数调用时,this 指向新创建的对象。
function Person(name) {
this.name = name;
}
const person = new Person('John Doe');
console.log(person.name); // 输出: John Doe
函数作为方法调用
当函数作为方法调用时,this 指向调用方法的对象。
const person = {
name: 'John Doe',
greet: function() {
console.log(this.name);
}
};
person.greet(); // 输出: John Doe
函数作为箭头函数调用
箭头函数没有自己的 this 指向。箭头函数的 this 指向与父作用域的 this 指向相同。
const person = {
name: 'John Doe',
greet: () => {
console.log(this.name);
}
};
person.greet(); // 输出: undefined
this 指向的特殊情况
在某些情况下,this 指向可能会有特殊的情况。例如,当函数在严格模式下调用时,this 指向 undefined。
"use strict";
function foo() {
console.log(this);
}
foo(); // 输出: undefined
总结
this 指向是 JavaScript 中的一个重要概念。this 指向的确定取决于函数的调用方式。函数作为普通函数调用时,this 指向全局对象。函数作为构造函数调用时,this 指向新创建的对象。函数作为方法调用时,this 指向调用方法的对象。函数作为箭头函数调用时,箭头函数没有自己的 this 指向,this 指向与父作用域的 this 指向相同。在严格模式下,函数的 this 指向 undefined。