Search code examples
javascriptadobe-brackets

function(exports) returns an error "Cannot set property 'weekDay' of undefined"


so I'm going through a 'Modules' Chapter of Eloquent JS book and I've encountered a problem with the function(exports) part.

(function (exports) {
var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
           "Thursday", "Friday", "Saturday"];

exports.name = function (number) {
    return names[number];
};
exports.number = function (name) {
    return names.indexOf(name);
};
})(this.weekDay = {});

console.log(weekDay.name(1));

returns

Cannot set property "weekDay" of undefined

However in the online editor on the book's website exactly the same code runs without problems and return "Monday".

I'm wondering if it's a problem with Adobe Brackets.


Solution

  • Use a module pattern that doesn't rely on being executed in a global script scope where this would be the global object. I recommend

    var weekDay = (function (exports) {
        var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
                   "Thursday", "Friday", "Saturday"];
        return {
            name: function (number) {
                return names[number];
            },
            number: function (name) {
                return names.indexOf(name);
            }
        };
    }());
    

    So yes, this was caused by your environment, but the code was fragile in the first place. If you want to continue to use that exports thing, you can also do

    var weekDay;
    (function (exports) {
        …
    })(weekDay = {});
    

    or alternatively check How to get the global object in JavaScript? and Getting a reference to the global object in an unknown environment in strict mode.