如何模拟“窗口"Nodejs中的对象? [英] How to emulate "window" object in Nodejs?

查看:39
本文介绍了如何模拟“窗口"Nodejs中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览器中运行时,所有附加到window"对象的东西都会自动成为全局对象.如何创建类似于 Nodejs 中的对象?

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

推荐答案

您可以为此目的使用预定义的对象 global.如果您将 foo 定义为 global 对象的一个​​属性,那么它将在之后使用的所有模块中可用.

例如,在 app.js 中:

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');

foo.js 中:

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

确保您没有使用 var 关键字,因为 global 对象已经定义.

Make sure you don't use the var keyword as the global object is already defined.

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

这篇关于如何模拟“窗口"Nodejs中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆