如何在Nodejs中模拟“窗口”对象?

在浏览器中运行时,附加到“窗口”对象的所有内容都将自动成为全局对象。 我如何创build一个类似于Nodejs的对象?

mySpecialObject.foo = 9; var f = function() { console.log(foo); }; f(); // This should print "9" to console 

你可以附加全局的东西来process而不是window

您可以使用预定义的global对象。 如果将foo定义为global对象的属性,则在之后使用的所有模块中都可以使用它。

例如,在app.js中

 var http = require('http'); var foo = require('./foo'); http.createServer(function (req, res) { //Define the variable in global scope. global.foobar = 9; foo.bar(); }).listen(1337, '127.0.0.1'); 

foo.js中

 exports.bar = function() { console.log(foobar); } 

确保您不使用var关键字,因为global对象已经定义。

有关文档,请查看http://nodejs.org/api/globals.html#globals_global

您可以使用GLOBAL对象。

 fruit = 'banana'; console.log(GLOBAL.fruit); // prints 'banana' var car = 'volks'; console.log(GLOBAL.car); // prints undefined 

我来到这个简单的解决scheme:

 var mySpecialObject = global; 

在正常浏览器中:

 var mySpecialObject = this; // Run this at global scope 

如果您要将Web控制台与在terminal中运行的节点(都是Javascript)进行比较:

window < – > global (注:GLOBAL已弃用)

在Web控制台中: window.wgSiteName (随机显示function)

在节点(terminal): global.url

document < – > process (注意:程序进程现在正在运行)

在Web控制台中: document.title

在节点(terminal): process.title