Purpose of passing global vars to self-invoking function or "IIFE" - javascript

I see a lot of this in older JavaScript
(function (w){
w.bar = 'baz';
})(window);
What is the advantage of the above, over
(function(){
window.bar = 'baz';
})();
same goes for any global variable, or variable defined outside the IIFE.

Makes it explicit that you are using (and probably modifying) globals in the function.
Allows you to modify the behavior in the future. Maybe you have a mockWindow for a unit test. Maybe you are using Node.js and you don't have a window, but want to add to the globals var instead.
p.s. IMO the trivial performance gain mentioned by #Rayon is a red herring.

In practice there is not much (any?) difference wit the example you have given, but you have probably oversimplified it from the code you are actually looking at.
In a more realistic program, you will have scopes and calls backs which are triggered and run in the eventloop asynchronously, and you are binding the variable to a specific instance in a closure -- so;
(function (w){
setTimeout(function(){w.bar = 'baz';},100);
})(window);
window = window2;
The bar is still being set in the original window, since that is what is bound to w - where in
(function (){
setTimeout(function(){window.bar = 'baz';},10);
})(window);
window = window2;
It will be set in the instance window2, since that is how the window is bound when the execution of the code eventually happens.
In this example "window" is a global variable, but the same is the case regardless of the scope of the variable that is bound.

Passing window is done because local variables are easier and faster to access than global variables ...this may show slight difference in performance . The method really comes in handy with module patterns and/or dependency injection .
Example
var moduleFirst = (function(){
var name = "harry";
return {
firstparam : name
}
})();
var moduleTwo = (function(x){
console.log(x.firstparam);
})(moduleFirst)
Output will be : harry
So when window gets passed in IIFE ; all of its revealed methods are available in a local variable .

By passing global objects like window, document, $ to IIFE(Immediately Invoked Function Expression) one can enhance the performance by reducing the scope lookup time.
Remember Javascript looks for property at first in local scope and way up chaining till global scope. So accessing window object at local scope reduce the lookup time.

Related

Why would you pass a global variable to a function?

I've seen the same code written both ways and wonder if there's any tradeoff between them.
Method 1:
(function(i) {
// Do something to i now
}(global_variable))
Method 2:
(function() {
// Do something to global_variable now
}())
Why would you pass a global variable to a function if it's going to exist in that scope anyway?
In this case, it gives clear instructions that this function uses a global and creates an easier to type alias. Also, it makes accessing the variable a little faster because it doesn't need to search all the scopes until it finds it in the global scope.
In the case of regular functions, not an iife as in your example, it makes your function more testable because you can mock the global that is passed in more easily.
for aliasing purposes for example:
(function(leeloo){
//inside here you can use the short term
})(LeeloominaiLekataribaLaminaTchaiEkbatDeSebat)
//this would be similar, it's a matter of preference
(function(){
var leeloo = LeeloominaiLekataribaLaminaTchaiEkbatDeSebat;
//...
})()
or to enclose a value, like this example:
(function($){
//in here, $ preserves the passed/injected value,
//even if the global value changes
})(jQuery.noConflict())
this way you could even use multiple versions of jQuery in the same page.
You might want to use the first example when you don't want to permanently change the value of global_variable, for some reason. E.g. after executing this code the local copy will be changed but the global variable will be unchanged.
global_variable=true; (function(i){ i=false; return i; }(global_variable));
This code however, obviously alters global_variable:
global_variable=true; (function(){ global_variable=false; }());
Edit: somewhat tangentially, this variation looks like it alters the global variable, but it doesn't because calling the function creates a shadow copy of the global variable. You should probably avoid this pattern since it's likely to create confusion:
g=true; (function(g){ g=false; return g; }(g));

Get the current scope of a Javascript Function [duplicate]

When I call a function, a local scope is erected for that call. Is there any way to directly reference that scope as an object? Just like window is a reference for the global scope object.
Example:
function test(foo){
var bar=1
//Now, can I access the object containing foo, bar, arguments and anything
//else within the local scope like this:
magicIdentifier.bar
}
Alternately, does anyone have a complete list of what is in the local scope on top of custom variables?
Background: I'm trying to get down to a way of completely shifting to global scope from within a function call, the with statement is a joke, call works a little better, but it still breaks for anything declared in function scope but not in global scope, therefore I would declare these few cases in global scope, but that requires me to know what they are. The IE function execScript makes a complete shift, but that only solves the problem for IE.
Note: To anyone loading JavaScript dynamically, setTimeout(code,1) is a simple effective hack to achieve global scope, but it will not execute immediately.
No, there's no way to reference the variable object of the execution context of a function binding object of the variable environment of the execution context (that's what that thing is called [now; hence the strikethrough]; details in §10.3 of the specification). You can only access the limited view to it you get with arguments (which is very limited indeed).
Usually when I've wanted to do this, I've just put everything I wanted on an object and then used that (e.g., passed it into a function). Of course, any functions created within the context have access to everything in scope where they're created, as they "close over" the context; more: Closures are not complicated.
I know this is hugely late, and you're probably not even slightly interested any more, but I was interested in the feasibility of this too and you should be able to make a work around of some sort using:
(function(global) {
var testVar = 1;
global.scope = function(s) {
return eval(s);
}
})(this);
then running:
scope('testVar'); // 1
returns the variable from within the closure. Not particularly nice, but theoretically possible to wrap that in an object, perhaps using some validation and getters and setters if you needed?
Edit: Having re-read the question, I assume you'd want to access it without having to specify a function in the scope itself, so this probably isn't applicable. I'll leave this here anyway.
Certain versions of Netscape had a magic property in the arguments object that did what you're looking for. (I can't remember what it was called)
What about something like this?
<script type="text/javascript">
var test = {
bar : 1,
foo : function () {
alert(this.bar);
}
}
test.foo();
</script>
You don't need a keyword to reference a variable in the local scope, because it's the scope you're in.

What does the global in (function(global){ some code .. })(this) do?

I was looking at adding comments to JSON and found this script that strips them out before processing making the JSON valid. I am just trying to understand how it works to make the JSON.minify() function available?
It starts with
(function(global){ ...
totally which is weird to me. I found that "global is a property of a RegExp instance, not the RegExp object" on MDN but I don't understand how it is works in this script if at all.
This snippet:
(function(global){
// your code here
// referring to the variable named "global" in this scope
// will be a reference to the default javascript global object
})(this);
is a construct for assigning the global object (whatever it might be) to an argument labeled global for all code that is inside this self-executing function.
The self executing function is used to define a separate execution scope so that any functions or variables you define inside this other scope will not interfere with or be directly accessible from outside this scope (insulating your scope from other code scopes).
In a browser, the global object is the window object, but if you intended to have code that might work in other javascript environments (like no node.js on a server) where the global object might not be window, this is a way of extracting the global value from the default this value, putting it into another variable which you can then refer to anywhere inside your code block.
For code mean to only run in a browser, there really is no point to this. You can just refer to window when you need the global object.
It's just a function parameter name. It might as well be froozboggles.
This code:
(function(foo) {
// In here, what's called "bar" in the outer scope is called "foo"
})(bar);
Defines an anonymous function taking one parameter bar and immediately calls it with the value of bar as the first parameter.
Apart from what jfriend00 mentions in his fine answer, it's also a good way of making sure that you don't leak variables and functions to the outer scope: If you declare, say, var baz = 17; in the top scope in javascript, it will be a property of window. If you wrap it in a function as in the pattern you mention, you can only export properties to window explicitly -- by assigning them to global, in the case of your example. Edit: As #josh3736 says in his comment, you can also leak to window by assigning without a previous declaration, e.g. quux = 4711;.

Why can deep nested function access top level vars?

I've been doing some javascript reading, and I've gathered that a closure has access only to the closure "wrapping" it, or, you might say it's immediate parent. Now I've been playing a bit, and I see in this jsfiddle that even deep nested functions have access to to vars defined way up.
Can anyone please explain that? Or explain what have I got completely wrong?
http://jsfiddle.net/tPQ4s/
function runNums() {
this.topVar = 'blah';
return function(){
(function() {
(function() {
console.log(topVar);
})();
})();
}
}
var someFunc = runNums();
someFunc();
Without going too deep into the details, a closure technically describes a array like variable within the such called Activation Object that is handled from the javascript engine. An ActivationObject contains Variables declared by var, function declarations and formal parameters.
That means, anytime a new function (-context) is invoked, internally a new Activation Object is created. That object is part of the new Execution Context, a typicall EC looks like:
this context variable
Activation Object
[[Scope]]
The interesting part here is [[Scope]]. That variable contains all Activation Objects of all parent context and is filled when the EC is called. So now, when a function wants to access a variable, the name resolution process first looks into its own Activation Object, if nothing is found the search continues in the "Scope chain", which is just an Indexed search through our [[Scope]] variable (which again, is an array of parent contexts). Thats why we also speak a lot about "lexical scope" in ECMA-/Javascript.
Note: The above behavior is not described entirely, that would need several pages of text. Also it describes the ECMAscript3 262 specification. Things work a little different in ES5, but its still around the same thing
That is because the chain runs further up to the top context.
In the example, that would be:
window < runNums < anonymous < anonymous < anonymous
Variables living in any of these will be available in the last anonymous function. In runNums, only variables living in runNums or window will be available. In the first anonymous function, only its variables and those living in runNums or window will be available, etc.
this is nothing but the Window object here.
Here runNums is a global function and runNums() is equal to window.runNums(). So this is window and this.topVar is window.topVar. Obviously it will be accessible from anywhere.
Try this and see the difference
var someFunc = new runNums();
someFunc();
The deep nested functions have not been executed. You did not return them for executing.

JavaScript: Reference a functions local scope as an object

When I call a function, a local scope is erected for that call. Is there any way to directly reference that scope as an object? Just like window is a reference for the global scope object.
Example:
function test(foo){
var bar=1
//Now, can I access the object containing foo, bar, arguments and anything
//else within the local scope like this:
magicIdentifier.bar
}
Alternately, does anyone have a complete list of what is in the local scope on top of custom variables?
Background: I'm trying to get down to a way of completely shifting to global scope from within a function call, the with statement is a joke, call works a little better, but it still breaks for anything declared in function scope but not in global scope, therefore I would declare these few cases in global scope, but that requires me to know what they are. The IE function execScript makes a complete shift, but that only solves the problem for IE.
Note: To anyone loading JavaScript dynamically, setTimeout(code,1) is a simple effective hack to achieve global scope, but it will not execute immediately.
No, there's no way to reference the variable object of the execution context of a function binding object of the variable environment of the execution context (that's what that thing is called [now; hence the strikethrough]; details in §10.3 of the specification). You can only access the limited view to it you get with arguments (which is very limited indeed).
Usually when I've wanted to do this, I've just put everything I wanted on an object and then used that (e.g., passed it into a function). Of course, any functions created within the context have access to everything in scope where they're created, as they "close over" the context; more: Closures are not complicated.
I know this is hugely late, and you're probably not even slightly interested any more, but I was interested in the feasibility of this too and you should be able to make a work around of some sort using:
(function(global) {
var testVar = 1;
global.scope = function(s) {
return eval(s);
}
})(this);
then running:
scope('testVar'); // 1
returns the variable from within the closure. Not particularly nice, but theoretically possible to wrap that in an object, perhaps using some validation and getters and setters if you needed?
Edit: Having re-read the question, I assume you'd want to access it without having to specify a function in the scope itself, so this probably isn't applicable. I'll leave this here anyway.
Certain versions of Netscape had a magic property in the arguments object that did what you're looking for. (I can't remember what it was called)
What about something like this?
<script type="text/javascript">
var test = {
bar : 1,
foo : function () {
alert(this.bar);
}
}
test.foo();
</script>
You don't need a keyword to reference a variable in the local scope, because it's the scope you're in.

Categories