简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM