问题
When running in a browser, everything attached to the "window" object will automatically become global object. How can I create an object similar to that in Nodejs?
mySpecialObject.foo = 9;
var f = function() { console.log(foo); };
f(); // This should print "9" to console
回答1:
You can use the predefined object global
for that purpose. If you define foo
as a property of the global
object, it will be available in all modules used after that.
For example, in 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');
And in foo.js:
exports.bar = function() {
console.log(foobar);
}
Make sure you don't use the var
keyword as the global
object is already defined.
For documentation, check out http://nodejs.org/api/globals.html#globals_global.
回答2:
you can attach global stuff to process
instead of window
回答3:
You can use the GLOBAL object.
fruit = 'banana';
console.log(GLOBAL.fruit); // prints 'banana'
var car = 'volks';
console.log(GLOBAL.car); // prints undefined
回答4:
I've come to this simple solution:
var mySpecialObject = global;
In normal browser:
var mySpecialObject = this; // Run this at global scope
回答5:
If you were to compare the Web Console to Node running in terminal (both Javascript) :
window
<-> global
(Note: GLOBAL is deprecated)
in Web Console : window.wgSiteName
(random to show functionality)
in Node (Terminal): global.url
document
<-> process
(Note: program process running right now)
in Web Console : document.title
in Node (Terminal): process.title
来源:https://stackoverflow.com/questions/14452409/how-to-emulate-window-object-in-nodejs