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);
})();
1
  • Version 1, 2, and 3 mix up magic and Magic. Commented Apr 28, 2016 at 10:30

1 Answer 1

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!');
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.