[英]'this' behaves differently in node environment than browser
I am following along with a tutorial about this
and execution context .我正在关注有关
this
和执行上下文的教程。 I observed that this code executes properly in the Chrome Console:我观察到这段代码在 Chrome 控制台中正确执行:
var globalThis = this
function myFunc () {
console.log('globalThis: ', globalThis)
console.log('this inside: ', this)
console.log(globalThis === this)
}
myFunc()
// globalThis: Window {...}
// this inside: Window {...}
// true
However, when I try to execute this same code in a node environment, I get this as a response:但是,当我尝试在节点环境中执行相同的代码时,我得到以下响应:
globalThis: {}
this inside: { console: [Getter],
global: [Circular],
process:
process {
title: 'node',
version: 'v8.16.2',
...
false
I understand that the global node this
value should be different from the browser javascript this
value, but the question is, why does myFunc's this
value not equal the global value?我理解全局节点
this
值应该和浏览器javascript this
值是不一样的,但是问题来了,为什么myFunc's this
值不等于全局值呢?
This is because the global scope of a node module is the same module, so if you execute console.log(this)
outside your function you are referencing the global scope of an empty module which is an empty object {}
, but when you execute the same console.log(this)
inside your function this
is going to point to the global Node scope (contains what you are seeing: console, global, process and a lot of other stuff), now if you are on strict mode, the scope inside of your function should be undefined
as it doesn't have a default local scope defined. This is because the global scope of a node module is the same module, so if you execute
console.log(this)
outside your function you are referencing the global scope of an empty module which is an empty object {}
, but when you execute function 中的相同console.log(this)
this
将指向全局节点 scope (包含您所看到的:控制台、全局、进程和许多其他内容),现在如果您处于严格模式, function 内部的 scope 应该undefined
,因为它没有定义默认的本地 scope。
Its a lot simpler on your browser where the global scope is the Window
object.它在您的浏览器上简单得多,全局 scope 是
Window
object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.