1

i.e. what's the equivalent of the browser's "window" object, to which top level functions are attached?

The following code succeeds in the REPL:

var assert = require('assert');
function foo() { };
assert.ok(foo == this["foo"]);

However in a script (or a module) it fails--in both cases "this" is an empty object.

I'm wondering about this so I can easily export all functions visible in a module's namespace--I want to be able to do something like:

function foo() { };
function bar() { };

["foo", "bar"].forEach(function (k) {
    exports[k] = ???;
});

(eval(k) works for the ???, but, ugh.)

1
  • The best I could figure out is to export the function when you define it: var foo = exports.foo = function(){...};. Or, you could create your own object containing the functions you'll later export: var fns = {}; fns.foo = function(){...}; ... fns.forEach(...); Commented Feb 27, 2011 at 14:42

1 Answer 1

1

Matt Ball's answer is pretty good:

var foo = exports.foo = function() {
  //...
};. 

// Or, you could create your own object containing 
// the functions you'll later export: 

var fns = {}; 

fns.foo = function(){...}; 

// ... 

fns.forEach(/*...*/); 

// – Matt Ball Feb 27 at 14:42

Alternatively,

exports.foo = {
  method1: function() { /*...*/ }
, method2: function() { /*...*/ }
, method3: function() { /*...*/ }
  /*...*/
}

Some modules which exhibit best practices: https://github.com/cloudhead/journey/blob/master/lib/journey.js For browser compat: https://github.com/caolan/async/blob/master/lib/async.js https://github.com/mikeal/request/blob/master/main.js

/fyi #node.js IRC welcomes you: http://bit.ly/nodeIRC

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.