sms343
sms343

Reputation: 63

Javascript Modules and Design Patterns

I have some questions about the way you can create modules in JavaScript. This is the syntax I found:

var Westeros;
(function (Westeros) {
    (function (Structures) {
        var Castle = (function () {
            function Castle(name) {
                this.name = name;
            }
            Castle.prototype.build = function () {
                console.log("Castle " + this.name)
            };
            return Castle;
        })();
        Structures.Castle = Castle;
    })(Westeros.Structures || (Westeros.Structures = {}));
    var Structures = Westeros.Structures;
})(Westeros || (Westeros = {}));

var winterfell = new Westeros.Structures.Castle("Winterfell");
winterfell.build();

I took this code from Mastering Javascript Design Patterns. However I've tried to find an answer why you need this line:

    var Structures = Westeros.Structures;

If you omit this line the code works as expected. Is there any explanation for this? Maybe to "reveal" the class?

Thanks!

Upvotes: 3

Views: 118

Answers (1)

Hydrothermal
Hydrothermal

Reputation: 5081

This code is horrifying. Here's a sample that does the exact some thing without all the pointless closures:

function Castle(name) {
    this.name = name;
}

Castle.prototype.build = function() {
    console.log("Castle " + this.name)
};

var Westeros = {
    Structures: {}
};

Westeros.Structures.Castle = Castle;

var winterfell = new Westeros.Structures.Castle("Winterfell");
winterfell.build();

When defining a "class" in ES5, all you have to do is declare a function with some arguments and place whatever initialization code you want inside. Methods are added to that function's .prototype property, and new objects using that class are created by calling its constructor function with the new keyword.

As for var Structures = Westeros.Structures;, it serves no purpose whatsoever. If you were to keep your original code sample, removing it wouldn't change anything. In fact, it can't be used even by more code further down because it's declared inside a closure and can't be accessed outside of that scope.

Upvotes: 1

Related Questions