Understand this in JavaScript Through a Simple Story

通过简单的故事了解 JavaScript 中的 this

用简单的故事了解 this 是什么

小明和小美是一对夫妻,他们住在芝麻街 34 号。有一天,小明或小美说:「这个房子太旧了,需要重新装修!」可以发现,这里的 this 就代指小明和小美所住的家,也就是「芝麻街 34 号」的意思。

但假设今天调用 this 的人不是小明和小美,而是另一个家庭,那么 this 会代表「另一个家」,而不是「芝麻街 34 号」。这个故事中的概念实际上与 JavaScript 的 this 一模一样!

什么是 this

简单来说,谁调用 this,this 就代表谁。

在 JavaScript 中,可以在全局以及函数执行环境中使用 this,此外 this 在严格模式🔗下的表现也会有所不同。下面会举例说明四种使用场景。

其中,直接在全局中使用 this 与在函数中使用 this 意义并不大(方法一、二),知道即可。

一、在全局中使用 this

如果直接打印 this,那么在浏览器中执行会是 window,在 node.js 中执行会是 global。

console.log(this === window); // true

二、在函数中使用 this

在非严格模式🔗下, this 会指向全局对象,也就是 window 或 global,这是因为执行环境(比如浏览器)认为你指的是 window.调用的函数 。

function show() {
console.log(this === window); // true
}
show();

但在严格模式下, this 会是 undefined,避免 this 莫名其妙地访问到全局对象,即使在嵌套函数中也是一样。

'use strict';
function show() {
console.log(this === undefined);
}
show();

三、在方法中使用 this

上学的孩子叫做「学生」,在对象中的函数就被称为「方法」。如果调用了一个方法,那么 JavaScript 就会将 this 指向该方法所属的对象。

function sayName() {
return `我的名字是: ${this.name}`;
}
const me = {
name: '小明',
sayName,
};
const you = {
name: '小美',
sayName,
};
me.sayName(); // 小明
you.sayName(); // 小美

四、在构造函数中使用 this

当使用 new 关键字创建一个新的对象时,JavaScript 就会将 this 指向该方法所属的对象。

function Student(name) {
this.name = name;
}
const student = new Student('小明');
console.log(student.name); // 小明

指定 this

前面提到 4 种使用场景,但有时会需要手动指定 this 的值,这时就可以使用 call()、apply()、bind() 三种方法。

总结

this 之所以让人困惑,是因为它需要基于上下文来判断,最简单的原则就是:谁调用 this,this 就代表谁。

参考资料