TheLazyChap
TheLazyChap

Reputation: 1902

Node's module.exports and IIFE confusion

I'm been playing around with node and Javascript IIFE and I'm a bit confused with node's modules.exports and how IIFE works in Javascript.

(function (Calculator) {
    var calculator = function () {
        var currentValue = 0,

            add = function (num) {
                return currentValue += num;
            };

        return {
            current: currentValue,
            add: add
        };
    }();

    module.exports = calculator;
}(module.exports));

The above code caused my tests to pass when I used the line module.exports = calculator; to export the module.

How come when I use to the parameter Calculator = calculator (note the case) causes my tests to all fail?

I thought Calculator (the parameter) refers to module.exports (the value that gets passed in?

In short:

Calculator = calculator; // Does NOT work

module.exports = calculator; // Does work

Upvotes: 1

Views: 2097

Answers (1)

j_walker_dev
j_walker_dev

Reputation: 1063

I thought this was interesting so i am going to add it. @dandavis is right about them being the same. But i just found out from playing with it you can change the global from the value passed in. Below does put calculator as the value for global module.exports. At least it did with this gulp stuff i am playing with. I am not a node expert though, so maybe its different in true node server land.

(function (Calculator) {
    var calculator = function() {
        var currentValue = 0,

            add = function(num) {
                return currentValue += num;
            };

        return {
            current: currentValue,
            add: add
        };
    }();

    Calculator.exports = calculator;

})(module);

Upvotes: 2

Related Questions