Startec Startec - 1 year ago 52
Node.js Question

What is the effect of passing exports to an anonymous function

I was looking at the code for the node-etherdream library and in the main module I saw this:


(function(ns) {
/// a bunch of code


I have never seen
being passed into an anonymous function like this, nor do I see
anywhere in this code. Yet, this file is being
d like any other module.

Can someone explain this use of
to me?

Answer Source

The exports is special object that you can set variables into. So in this example when the function executes it passes this object exports.

If you want to export some variable you can set it in ns variable(exports) in this case like that:

(function(ns) {
/// a bunch of code
    ns.func1 = function(){}

    ns.func2 = function(){}

    ns.age = 20

When you require the file from other file you will get access to this variables func1, func2 and age like that:

var o = require('file.js')
o.age // => 20
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download