How do these patterns differ?

How to do it:

var obj = obj || {}; obj.Something = (function() { function Something() { }; Something.prototype.someMethod = function() { }; return Something; })(); 

differ from this:

 obj.Something = function() { }; obj.Something.prototype = { }; 

How are the patterns different? When will I use one over the other?

+6
source share
3 answers

The main reason why you will use what your teacher recommends is to define other variables and functions that will not be displayed in the global scope.

For instance:

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

Here, sum not public and does not pollute the global namespace.

In addition, both templates are pretty similar. But it's nice to get used to the IIFE pattern especially when, like you, you are trying to understand why this is useful, and not just apply it.

+8
source

I think he models more after the OOP approach. Its syntax resembles the definition of a class, which can make it more "useful" according to its words.

+1
source

In his example, he almost made a closure. You should read about it. If it had any variable in the context of a self-named function, you would have a closure.

Also note that in your teacher example, something has a function on its prototype. In your example, you deleted the prototype Something, replacing it with an empty one.

+1
source

Source: https://habr.com/ru/post/945007/


All Articles