2

In regular browser js, we can do this:

window["fname"] = function(){ /* do something */ };

then we can call fname where ever we want - it is now a global function. Is it possible to do a similar thing in node, where we add functions to a certain object and they can be called as is in the rest of the file:

root["fname"] = function(){ /* do something */ };
fname();

I'm not looking for a something that acts globally over all files, just something that would keep the "global namespace pollution" in this file that I can call all of these functions as is, without resorting to obj.fname.

Callum Rogers
  • 15,630
  • 17
  • 67
  • 90
  • Here is a similar question: http://stackoverflow.com/questions/3691453/javascript-function-change-variables-scope Hope it helps. – Pato Sep 05 '11 at 21:13
  • Yeah, he can use **with**, but its **evil** - http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/ ;] – Adam Jurczyk Sep 06 '11 at 11:55
  • Nope, `with` is not an option as it does not allow access to other variables which do not need that prefix. See [my code](https://github.com/CRogers/coml) to understand what I was trying to do and how it relates to this question. – Callum Rogers Sep 06 '11 at 12:28
  • oh, i see what you want to do... hmmm, i have no idea how to it ^^ Maybe you could try look into codebase of Firebug debugger? – Adam Jurczyk Sep 06 '11 at 15:32
  • It works now :p You just need to wrap the "view" in a self running function. – Callum Rogers Sep 06 '11 at 17:34
  • Could you post some example here, what exactly you done to solve your problem? – Adam Jurczyk Sep 06 '11 at 21:06

2 Answers2

2

EDIT (for clarity):

As far my test showed - you can't access local scope of a module. It is (or is like) closure, and you cant programatically acces its scope. So your best bet is global (aka root) object, which keeps global vars, BUT it is the same for whole app (so every module has acces to it).

So, the best you is making shortcuts each time:

var foo = myModule.foo;
var boo = myAnotherModule.boo;

Use 'global' as namespace:

global['foo'] = function(){ console.log('foo'); }; // same as global.foo = ...

foo() //prints 'foo' to console

More here:

http://www.reddit.com/r/node/comments/jb4dy/adding_to_the_global_namespace_in_nodejs/

Adam Jurczyk
  • 2,153
  • 12
  • 16
  • See the related documentation: http://nodejs.org/docs/v0.5.3/api/globals.html#global . And `global.foo = ...` is just the same as `global['foo'] = ...` – nponeccop Sep 05 '11 at 20:01
0

root was the object I wanted:

root["foo"] = function(){ /* blah */ }
foo();
Callum Rogers
  • 15,630
  • 17
  • 67
  • 90
  • 2
    Yeah, but `root` is the same object as `global` (and `GLOBAL`). You can try executing `root===global` or look at output of `console.log(root)`, there you have `global: [Circular]` which states for self refference. – Adam Jurczyk Sep 06 '11 at 11:31