front-end-interview-handbook/packages/quiz/questions/explain-how-this-works-in-j.../zh-CN.mdx

19 lines
1.9 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 解释 JavaScript `this` 如何工作
---
`this`没有简单的解释;它是 JavaScript 中最令人困惑的概念之一。 一个简短的解释是,`this`的值取决于函数如何调用。 在线阅读了很多关于`this`的解释,[Arnav Aggrawal](https://med.com/@arnav_aggarwal)的解释很清楚。 适用下列规则:
1. 如果调用函数时使用 `new` 关键字,那么函数中的`this` 是一个全新的对象。
2. 如果`apply`, `call`, 或 `bind` 用于调用/创建函数, 那么函数中的`this` 是作为参数传递的对象。
3. 如果一个函数作为方法被调用,例如`obj.method()` -- `this`是该函数的一个属性对象。
4. 如果一个函数被作为一个自由函数调用, 意思是在没有上述任何条件的情况下调用它,`this `就是全局对象。 在浏览器中,它是 `window ` 对象。 如果在严格模式下(`'use strict'`)`this`将是`undefined ` 而不是全局对象。
5. 如果上述多条规则都适用,则排名靠前的规则获胜,并将设置`this`值。
6. 如果函数是一个 ES2015 箭头函数, 它将无视上面的所有规则,并在创建时接收其周围范围的`this`值。
若要深入解释,请查阅他的[Medium 上面的文章]\(https://codeburst.io/the-simple-rules-this in javascript-35d97f31bde3)。
#### 你能否举例说明在 ES2015 年处理这一问题的方式已经发生变化?
ES2015 允许您使用[箭头函数](http://2ality.com/2017/12/alternate-this.html#arrow-functions)来使用[封闭的词汇范围](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this). 这通常很方便,但确实阻止了调用者通过`.call`或`.apply`控制上下文--后果是诸如`jQuery`这样的库不会在你的事件处理函数中正确绑定`this`。 因此,在重构大型遗留应用程序时必须牢记这一点。