Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do these patterns differ?

Tags:

javascript

How does this:

var obj = obj || {};

obj.Something = (function() {

    function Something() {

    };

    Something.prototype.someMethod = function() {

    };

    return Something;

})();

differ from this:

obj.Something = function() {

};

obj.Something.prototype = {

};

How do the patterns differ? When would I use one over the other?

like image 442
user2251919 Avatar asked May 14 '13 19:05

user2251919


2 Answers

The main reason why you would use the way your teacher recommends is that you may define other variables and functions that wouldn't be exposed in the global scope.

For example :

obj.Something = (function() {
    var sum = 0;
    function Something() {
    };
    Something.increment = function(){ sum++ };
    Something.getSum = function(){ return sum };    
    return Something;
})();

Here the sum isn't public and doesn't pollute the global namespace.

Other than that, both patterns are pretty similar. But it's a good idea to get accustomed to the IIFE pattern especially when, as you do, you try to know why it's useful and not just apply it.

like image 160
Denys Séguret Avatar answered Sep 18 '22 23:09

Denys Séguret


I think he is modeling more after an OOP approach. His syntax resembles a class definition, which may make it more "usable" according to his words

like image 44
75inchpianist Avatar answered Sep 18 '22 23:09

75inchpianist