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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With