0

I'am decided to "go deeper" with javascript, and before ECMA6 to try to master ECMA5 skills, and now i am stuck with object creation and initialization, what version is better, more practical, better to read and so on. Which one to stuck with and use as foundation. So what i am tried:

Version 1, and is most popular in guides found googling

;(function() {
    var magic = magic || {};

    magic.doStuff = function() {
        alert('Magic');
    };

    window.magic = magic;
    document.addEventListener('DOMContentLoaded', function() {
        magic.doStuff();
    }, false);

})();

Version 2, quite as same as version 1, just a little bit different syntax

(function () {
    var magic = {
        doStuff: function() {
            alert('Magic');
        }
    };

    document.addEventListener('DOMContentLoaded', function () {
        magic.doStuff();
    }, false);
})();

Version 3, this one is worst for me, difficult syntax, more space for mistakes, and i am not even sure is it writen correctly

(function () {
    var magic = (function () {
        magic.doStuff = function () {
            alert('Wow!');
        };

        return magic;
    });

    document.addEventListener('DOMContentLoaded', function () {
        (new magic()).doStuff();
    }, false);
})();

Version 4, this one was shown to me by senior dev, not so popular in guides, or it's just i didn't noticed it, but after some explanation probably is my favourite.

(function() {
    var magic = (function () {
        function publicDoStuff() {
            alert('Magic');
        }

        return {
            doStuff: publicDoStuff
        };
    })();

    document.addEventListener('DOMContentLoaded', function () {
        magic.doStuff();
    }, false);
})();
Itsmeromka
  • 3,621
  • 9
  • 46
  • 79

1 Answers1

1

I like to keep it simple for simple objects

var magic = {
    doStuff: function () {
        alert('Wow!');
    },
};

document.addEventListener('DOMContentLoaded', function () {
    magic.doStuff();
}, false);

If you use many instances of an object, then its faster to use prototype

Magic = function() {
};

Magic.prototype.doStuff = function() {
    alert('Wow!');
};
C14L
  • 12,153
  • 4
  • 39
  • 52