首页 > 解决方案 > 三种不同 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 给我不同的输出吗?

标签: javascriptnode.jsv8deno

解决方案


三种不同 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)。


推荐阅读