jeudi 29 septembre 2016

Module Pattern: var module = new function() {...} vs. var module = (function () {...}());

The Title is a very shorthand to the actual comparison I will give below. I'm delving into JavaScript and also read about the Module Pattern (JavaScript Module Pattern: In-Depth and Mastering the Module Pattern)

An implementation of my own of the Module Pattern was slightly different than the described pattern in the links above.

My implementation:

var smath1 = new function () {
        // "private fields"
        var answer = new Number(42);

        // "public fields"
        this.PI = new Number(3.141592653589793);

        // "private functions"
        function getHalfTheAnswer() {
                return answer / 2;
        };

        // "public functions"
        this.sum = function (a, b) { return new Number(a) + new Number(b) };
        this.mul = function (a, b) { return new Number(a) * new Number(b) };
        this.getTheAnswer = function () { return answer; };
        this.calcTheAnswer = function () { return getHalfTheAnswer() * 2 };
}

I'm interested in how this is different (technically/logically) from the Pattern described in the links...

var smath2 = (function () {

        var my = {};

        // "private fields"
        var answer = new Number(42);

        // "public fields"
        my.PI = new Number(3.141592653589793);

        // "private functions"
        function getHalfTheAnswer() {
                return answer / 2;
        };

        // "public functions"
        my.sum = function (a, b) { return new Number(a) + new Number(b) };
        my.mul = function (a, b) { return new Number(a) * new Number(b) };
        my.getTheAnswer = function () { return answer; };
        my.calcTheAnswer = function () { return getHalfTheAnswer() * 2 };

        return my;
}());

...and what makes the second approach superior/preferable to the first, if so at all?

The usage would be exactly the same as well as the behavior as far as I could see in my tests. See the fiddle: JS Module Pattern

Aucun commentaire:

Enregistrer un commentaire