Understanding Iife
Solution 1:
Your current code works because img_path is actually global and your IIFE is useless. You may do:
var img_path=(function(){
var img=document.getElementByTagName("img");
var img_path=[];//now localfor (var i=0;i<img.length;i++){
img_path.push( newStore(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
}
return img_path
})()
Now theres an enclosed img_path and img array and a global img_path.
Note that you could also do:
var img_path=document.querySelectorAll("img").values().map(el=>newStore(el.src,el.getAttribute("data-color")));
Solution 2:
The reason why img_path
is global has nothing to do with IIFE. It is global because you have not declared it with the var
keyword. Everything that is not declared with var
(or const
, or let
) will be attached to the global scope, in your case it will be attached to the window
object. Just try console.log(window.img_path)
after your IIFE (or not IIFE) code version.
I would recommend you start using use strict
in your js, as it will point out more "unobvious" errors.
Solution 3:
The IIFE here is not really the part that's blowing your mind.
In JavaScript, you must declare your variables. If you are using JS in the browser, and you aren't using strict-mode (you should be, once you have a better handle on the language), you'll know why these things are occurring.
var x = 1;
function makeGlobalsHappen () {
y = 2;
var z = 4;
}
makeGlobalsHappen();
x; // 1
y; // 2
z; // ERROR! z is not defined
That had nothing to do with the IIFE (of which, I have none).
Were I in ES5's opt-in strict-mode, or using modern JS modules (which are strict by design):
const x = 1;
constmakeGlobals = () => {
y = 2; // ERROR! y is undefinedconst z = 4;
};
makeGlobals(); // *BOOM*
Solution 4:
You should care a bit more about semicolons, they're not for leisure but because you need them. There are edge cases where ambiguity is introduced without semicolons. That said, you don't need the function namen and you don't need to return anything if you don't use the result by any means (as an argument or an assignment). You also don't need the store function, it really doesn't do much, just use JS object literals as shown below. The function may also be written as:
(function () {
"use strict";
var i, img_path;
img_path = [];
for (i = 0; i < img.length; i++)
{
img_path.push({
"path": img[i]["src"],
"color": img[i]["data-color"]
});
}
// TODO: use img_path here because outside this function scope it does not exist
}());
// ^ better parens placement
For more information on how to write clean code and adhere to open-source JS style look up JSLint and similar tools. You'll see how many style errors such a tool gives you.
Post a Comment for "Understanding Iife"