0

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.

matveytn
  • 793
  • 1
  • 5
  • 8
  • Omit the `this.` and everything will be fine. Looks like you're trying to assign to a variable, not create a property on some object that you don't know (and that apparently doesn't exist here). – Bergi Dec 15 '15 at 02:03
  • @Bergi Yes, that works! thank you. I, however, wonder why it works with _this_ on the website [here](http://eloquentjavascript.net/10_modules.html), it's under **Objects as interfaces** part. – matveytn Dec 15 '15 at 02:12
  • As the next paragraph says, "*The previous pattern is commonly used by JavaScript modules intended for the browser.*", in which case "*Outside of a function, `this` refers to the global scope object.*" – Bergi Dec 15 '15 at 02:24

1 Answers1

1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375