javascript - 三种不同 JS 引擎的三种不同 `this` 行为
问题描述
我正在学习this
关键字以及它在常规函数与 ES6 箭头函数和函数表达式方面的不同含义,当我尝试在 Chrome、Deno 和 Node.js 中运行以下代码时遇到了一些奇怪的事情。所以我准备了以下内容:
示例:
function foo(n) {
console.log("***Begin Foo****")
console.log(`n = ${n}\nthis = ${this}\nthis.count = ${this.count}`)
console.log("****End Foo****")
this.count++;
}
var count = 1;
for (let i = 0; i < 5 ; ++i) {
foo(i)
}
console.log("From global this.count = "+this.count)
console.log(this)
德诺输出:
PS E:\webdev\js_scratchspace> deno run .\another_this.js
***Begin Foo****
error: Uncaught TypeError: Cannot read property 'count' of undefined
console.log(`n = ${n}\nthis = ${this}\nthis.count = ${this.count}`)
^
at foo (file:///E:/webdev/js_scratchspace/another_this.js:24:64)
at file:///E:/webdev/js_scratchspace/another_this.js:31:5
节点输出:
PS E:\webdev\js_scratchspace> node .\another_this.js
***Begin Foo****
n = 0
this = [object global]
this.count = undefined
****End Foo****
***Begin Foo****
n = 1
this = [object global]
this.count = NaN
****End Foo****
***Begin Foo****
n = 2
this = [object global]
this.count = NaN
****End Foo****
***Begin Foo****
n = 3
this = [object global]
this.count = NaN
****End Foo****
***Begin Foo****
n = 4
this = [object global]
this.count = NaN
****End Foo****
From global this.count = undefined
{}
铬输出:
***Begin Foo****
n = 0
this = [object Window]
this.count = 1
****End Foo****
***Begin Foo****
n = 1
this = [object Window]
this.count = 2
****End Foo****
***Begin Foo****
n = 2
this = [object Window]
this.count = 3
****End Foo****
***Begin Foo****
n = 3
this = [object Window]
this.count = 4
****End Foo****
***Begin Foo****
n = 4
this = [object Window]
this.count = 5
****End Foo****
From global this.count = 6
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
根据我对此的理解,对于箭头函数this
没有显式绑定,并且是指this
定义箭头函数的范围,而对于常规函数this
是指调用它的上下文,Chrome的输出似乎是最有意义的大部头书。例如,我不明白为什么 Node 不会将全局对象识别为this
. 我对 Deno 的输出最不感兴趣,因为我想我可能不明白它到底想做什么。
有人可以解释为什么 Node、Deno 和 Chrome 给我不同的输出吗?
解决方案
三种不同 JS 引擎的三种不同
this
行为
这是一种误导性的说法。您拥有三个不同的 JS 环境,但它们都使用相同的引擎。
我被 Node 给我弄糊涂了
this = {}
。
这不是它给你的:this = [object global]
。
您在 Node 中没有看到的内容var count
显示为this.count
. 获得这种行为的一种方法(我不知道 Node 是否正在这样做)是将整个代码包装在 IIFE 中。如果你这样做:
(function() {
/* YOUR CODE HERE... */
})();
在 Chrome 中,您会看到相同的行为,因为 thenvar count
只是一个函数局部变量。
正如@Barmar 所说,通过默认为严格模式(除了将代码包装在 IIFE 中),你会得到 Deno 的行为。
this
结论:在全局范围内依赖并不是一个好主意。尝试this
仅用于将在对象上调用的方法(例如,如果您有foo.bar()
任何地方,那么 的主体bar() {...}
可以this
用来引用foo
)。
推荐阅读
- javascript - 如何修复不在 phaser.js 中加载的图像
- python - 有没有办法可视化网格?
- apache-spark-sql - 具有两列的平面图
- python - CSV 中的 URL 抓取列表给出了未知的 URL 类型错误
- java - 从活动的 onCreate 中已运行的服务中获取数据
- c - 测试和学习 C 中的图时出现意外错误
- c++ - 从 CSV 文件中读取数据并尝试将数据加载到由结构组成的向量中?
- java - JavaFX PropertyValueFactory 无法检索属性
- apache-spark - 在 Google Colab 上工作时如何打开 Spark UI?
- tensorflow - 使用 Keras 时,第一层的权重在训练后不会改变