我正在关注有关this
和execution context 的教程.我观察到此代码在 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
但是,当我尝试在 Node 环境中执行相同的代码时,我得到了这样的响应:
globalThis: {}
this inside: { console: [Getter],
global: [Circular],
process:
process {
title: 'node',
version: 'v8.16.2',
...
false
我明白全局 Node 的this
值应该和浏览器javascript的this
值不同,但是问题是,为什么myFunc的this
值不等于全局值?
最佳答案
这是因为 Node 模块的全局作用域是同一个模块,所以如果你在你的函数之外执行 console.log(this)
你是在引用一个空模块的全局作用域,它是一个空对象 {}
,但是当您在函数中执行相同的 console.log(this)
时,this
将指向全局对象 Node 范围(包含您所看到的:控制台、全局、进程和许多其他内容),现在如果您处于严格模式,则函数内部的范围应该是 undefined
因为它没有没有定义默认的本地范围。
在全局作用域是 Window
对象的浏览器上要简单得多。
关于javascript - “this”在 Node 环境中的行为与浏览器不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848955/