module - Difference between an IIFE and non-IIFE in JavaScript Modular approach -
recently while trying learn more iife , modules in javascript question came mind how iife making module while not invoking function doesn't make module..
can share me difference between code
var module = (function () { var = {}, privatevariable = 1; function privatemethod() { // ... } my.moduleproperty = 1; my.modulemethod = function () { // ... }; return my; }());
and code function not invoked..
var module = function () { var = {}, privatevariable = 1; function privatemethod() { // ... } my.moduleproperty = 1; my.modulemethod = function () { // ... }; return my; };
does second block of code means module function returns object?
if use second variable
var moduleobj = module();
will work same first code block shared iife.. kind of confused...
yeah pretty got idea of difference between two, let's @ why might want 1 on other.
an iife useful isolate scope. lets keep variables define private inside iife without polluting global space around it. it's nice way compose function has variables don't need lurking around. let's minimize example bit.
var counter = (function () { var count = 0; var counter = { add: function () { count++; }, subtract: function () { count--; }, getcount: function () { return count; } } return counter; })(); counter.add(); counter.add(); counter.getcount(); // 2 counter.subtract(); counter.getcount(); // 1
what happens above we're able compose "counter" functionality without leaking private information, count
. it'd bad if other things override accident. happens right away can assign counter
result of iffe -- counter
set of functions. counter
equal that, , counter
able retain access count
since defined in same scope.
the benefit here we're able assign variable composition of functionality. iife allows immediately return return
inside of it. since assign counter
iife, , iife returns functionality inside of it, counter
functional component.
we don't have use iife. it's handy when want "tuck away" implementation details , return api.
so, if had same thing, wasn't iife -- function?
just example, we'd have call in order "instance".
var counterfactory = function () { var count = 0; var counter = { add: //... subtract: //... getcount: //... }; return counter; }; var countera = counterfactory(); var counterb = counterfactory(); countera.add(); countera.add(); countera.getcount(); // 2 counterb.add(); counterb.getcount(); // 1
see difference? it's function returning. in first example single counter
instance, may fine. in second example, it's more of "factory" -- generates instance of counter
, can call multiple times , multiple instances of it.
Comments
Post a Comment