How to emulate “window” object in Nodejs?

 ̄綄美尐妖づ 提交于 2020-03-21 11:43:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!