wewea / wewea.github.io

Blog in issue:laughing:
0 stars 0 forks source link

[坑] javascript和node.js中global的区别 #3

Open wewea opened 9 years ago

wewea commented 9 years ago
  1. javascript的top-level-scope是global scope, 但是在node.js中top-level-scope是被隐藏在module内的.

同样的代码在node命令行和运行脚本的结果竟然不一样

// interactive mode
console.log(this === global) // => true

// execute file
console.log(this === global) // false

但是在node中在函数中如果有this, 直接进行函数调用仍然是绑定到global object

// foo.js
function foo() {
 console.log(this === global); // true
}

console.log(this) // => {} 

download

直到我RFTM

global# {Object} The global namespace object. In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside an Node.js module will be local to that module.

参考: Node.js 启动方式:一道关于全局变量的题目引发的思考