简体   繁体   中英

Why do we need IIFE's to have module scoping in Javascript?

Suppose I have core.js

var ajax = function(){};
var something = function(){super};
var globalconstant = 5;
var someutilitymodule = {
onekey: something;
twokey: something;
}

If I include this in my file as <script src="core.js">

1) I pollute the global namespace

2) Might [replace/get replaced by] another variable .

However won't making it an Object solve the problem ? Ie I make core.js like this

core = 
{
    ajax : function(){},
    something : function(){super},
    globalconstant : 5,
    someutilitymodule = {
                        onekey: something;
                        twokey: something;
                        }
}

What is the fundamental problem in this approach ? Is it because that you can't access other items until the full Object is created ? Like for example core = {a:"Foo" , b:a} won't work ? However I could solve it by

core = {};
core.a="Foo";
core.b=core.a;

Why do we have to get into IIFE(Immediately Invoked Function Expression) if we are not really interested in closures ? For "module namespace" in Javascript that doesn't mind having everything public in a different namespace , won't this approach work and create Module effect in Javascript ?

Are there any pointers to read more on this ? I know its a bit vague but I am new to this concepts like IIFE requirejs etc . So trying to understand from a newbie perspective .

This question is related to JavaScript - Advantages of object literal .

"Object Literal Notation" is techincal term for this . It is one of the commonly used patterns for segregating code in JavaScript although Module Pattern like http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/ is the more advanced form and it uses IFFE just to get extra features like private variables using closures .

However IFFE variables can't be accessed at a later point unless you define methods in the function right away . You can't extend methods to use this IIFE variables later on .

For example :

//counter here is the iife functions' counter variable
var module = (function(){var counter=1; return {getCounter: function(){return counter}}})()

//counter here is the global counter variable as it was created from the global scope
module.setCounter = function(arg){counter = arg + counter}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM