我正在学习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 给我不同的输出吗?
this
三种不同 JS 引擎的三种不同行为
这是一种误导性的表达方式。您有三个不同的 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
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句