The need for JS functions which are self executing? - javascript

What is the use of functions which self execute?
(function(w,d) {...})(window, document);
And why do they pass window/document which are global variables?

The reasons are:
We need to create private scope, everything declared inside that function is not polluting the global namespace.
Keeping code readable with shorter names. This is for your question: why do they pass window/document which are global functions?
Update: add 1 more reason
Create closure to capture variable inside a loop.
For example:
for (var i=0 ; i< count; i++ ){
(function(index){
//do something with current index
})(i);
}
This is usually the case when you need to do something later on after the loop has finished and still need to have reference to the index. Like attaching click event handlers for a list of objects or using setTimeout
Bonus:
Due to self-executing function's ability to create private scope. There comes Javascript module design pattern. The idea of the pattern is to create a private scope for your private variables and methods (truly private), only public things that are needed to avoid polluting global scope

What is the use of functions which self execute?
This is an anonymous function, which is immediately called. The purpose of this is that if the function doesn't need to be called from anywhere else, you don't clutter up the namespace with making up random names. Such functions are often used as callbacks or event handlers.
And why do they pass window/document which are global functions?
In a page with FRAME or IFRAME tags, or pop-up/open-in-new-window pages, there may be more than one window and document.

The idea is you pass copies of the global variables so anything you change within the scope of your self-executing function does not affect the external reference. It also allows you to declare global variables within that function which won't clash with existing variables.
In a nutshell, the goal here is to restrict scope.

Why do they pass window/document which are global functions?
So that inside that function scope window and document will be available as w and d.
One of the common practice of this is included with jQuery plugin development as:
(function($) {
//...
})(jQuery);
Since $ can be used in prototype too, this can create anamolities when mixing two libraries, but inside above function, $ will only represent jQuery but not prototype.

Self executing functions also called as Immediately-Invoked Function Expression(IIFE) have multitude of uses. The most common ones are:
Prevent pollution (using closure)
Its a better practice to envelope all your code into a function scope to avoid littering the global namespace.
"Variables and functions defined within a function may only be accessed inside, but not outside, that context, invoking a function provides a very easy way to create privacy."link
Class-based inheritance design:
JavaScript has prototypal inheritance. But lot of class-based custom implementations are out there which use self-executing functions [1]
Global and window objects are passed for easier references. Changes to the properties of these objects DO reflect outside too.. The changes you make to w and d does reflect/change outside. These local variables are mere references to the global window and document. Hence, changes made inside the function scope will make global changes! [fiddle]

These are anonymous functions being used as closures returning a function or a collection to functions with access to a set of common captured variables declared in their common parent function closure, not polluting the global namespace and being passed around.
Very basic exemple:
keepsTrackOfTimesUsedWithoutPollutingNamespace = function()
{
var right = 0;
var left = 0;
display = function(){console.log("right got executed " +right+" times and left got executed " + left +" times.\n";}
return [
function()
{
right += 1;
display();
},
function()
{
left += 1;
display();
}
]
}

Related

javascript closure scope chain- how to see the variables bound to the scope chain?

Javascript functions are objects and they have scope chain associated with them.
If some closure exists with a function that has a different scope chain than the one that was in effect when they were defined.As an example invoking function is a returned function object from some other (parent) function that had a scope chain with a large number of private variables,
so invoking function will use the already existing inherited scope chain of parent function as well as bounded old variables.
Is there any way to check the variables associated with the scope chain without looking into the parent function?
Ideally one has to keep track of defined variables in the parent function, my question is without lookup of the parent function, can we see the variables associated with scope chain?
If yes (any method?) can we check the current value of variables associated with scope chain?
Also can someone give the structure of scope chain( at least i know its not like CPU stack like strucuture but something else?).
Scoped variables are available to the functions created in the same context (JavaScript is functionally scoped).
You have access to them but you can't run a method to report them. If this is a common requirement, I suggest keeping internal variables handy in a "config" variable:
var obj = (function (config) {
return {
getTest: function () {
return config.test;
}
};
}({test: 1}));
Nick Zackas has done a good presentation about the scope chain (I think it's here: http://googlecode.blogspot.com/2009/06/nicholas-c-zakas-speed-up-your.html)
Otherwise, use a browser with developer tools like Chrome (Firebug often forgets what the scoped variables are).

Javascript explain this code please

I see in a lot of scripts this pattern
(function(){})();
What is it and why use it?
It's used to force the creation of a local scope it avoid poluting the current (often global) scope with the declarations.
It could be rewritten like this if you want to avoid the anonymous function :
var scope = function() { /*...*/ };
scope();
But the anonymous function syntax have the advantage that the parent or global scope isn't even poluted by the name of the function.
(function() { /*...*/ })();
It's also a good way to implement information hiding in javascript as declarations (functions and variables) in this scope won't be visible from the outside. But they could still see each other and as javascript implement closures functions declared inside such a scope will have access to other declarations in the same scope.
That is defining a function with no name, and immediately calling it. Because Javascript functions act as closures -- a persistent scope -- this is a useful way to create a set of interconnected objects or functions.
An anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to an identifier.
This is the basic syntax for creating a closure. More typically, it'd contain some code:
(function(){
//Your Code Here
})();
This is equivalent to
var some_function = function() {
//Your Code Here
};
some_function();
The biggest reason for doing this is cleanliness; any variables declared outside of any function are global; however, variables declared inside of this function are contained inside of this function and won't affect or interactive with any code outside of the function. It's good practice to wrap any kind of reusable plugin in a closure.
It's immediately executing anonymous function.
It's basically the same as:
var test = function(){};
test();
but does not require usage of additional variable.
you need to wrap it in additional parenthesis to get the function as a result of your expression - otherwise it's understood as function declaration, and you can't execute a declaration.
it's mostly used for scope protection - because JS has functional scope, every variable defined as var x; inside such function will be kept in it's function local scope.
all of this simply means 'immediately execute everything inside this function without polluting the global scope'.
it's also commonly used in well known patterns, such as module pattern and revealing module pattern. please see http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth for more detail.
It is called an immediate function or an anonymous closure and is the basis of the module pattern.
It is used to create a private local scope for code.

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.

JavaScript: Why the anonymous function wrapper? [duplicate]

(function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
With the increasing popularity of JavaScript frameworks, the $ sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:
(function ($){
// Your code using $ here.
})(jQuery);
Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $ to refer to that object, without worrying about other frameworks being in scope as well.
This is a technique used to limit variable scope; it's the only way to prevent variables from polluting the global namespace.
var bar = 1; // bar is now part of the global namespace
alert(bar);
(function () {
var foo = 1; // foo has function scope
alert(foo);
// code to be executed goes here
})();
1) It defines an anonymous function and executes it straight away.
2) It's usually done so as not to pollute the global namespace with unwanted code.
3) You need to expose some methods from it, anything declared inside will be "private", for example:
MyLib = (function(){
// other private stuff here
return {
init: function(){
}
};
})();
Or, alternatively:
MyLib = {};
(function({
MyLib.foo = function(){
}
}));
The point is, there are many ways you can use it, but the result stays the same.
It's just an anonymous function that is called immediately. You could first create the function and then call it, and you get the same effect:
(function(){ ... })();
works as:
temp = function(){ ... };
temp();
You can also do the same with a named function:
function temp() { ... }
temp();
The code that you call jQuery-specific is only that in the sense that you use the jQuery object in it. It's just an anonymous function with a parameter, that is called immediately.
You can do the same thing in two steps, and you can do it with any parameters you like:
temp = function(answer){ ... };
temp(42);
The problem that this solves is that it creates a closuse for the code in the function. You can declare variables in it without polluting the global namespace, thus reducing the risk of conflicts when using one script along with another.
In the specific case for jQuery you use it in compatibility mode where it doesn't declare the name $ as an alias for jQuery. By sending in the jQuery object into the closure and naming the parameter $ you can still use the same syntax as without compatibility mode.
It explains here that your first construct provides scope for variables.
Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:
(function() {
var myProperty = "hello world";
alert(myProperty);
})();
alert(typeof(myProperty)); // undefined
Another reason to do this is to remove any confusion over which framework's $ operator you are using. To force jQuery, for instance, you can do:
;(function($){
... your jQuery code here...
})(jQuery);
By passing in the $ operator as a parameter and invoking it on jQuery, the $ operator within the function is locked to jQuery even if you have other frameworks loaded.
Another use for this construct is to "capture" the values of local variables that will be used in a closure. For example:
for (var i = 0; i < 3; i++) {
$("#button"+i).click(function() {
alert(i);
});
}
The above code will make all three buttons pop up "3". On the other hand:
for (var i = 0; i < 3; i++) {
(function(i) {
$("#button"+i).click(function() {
alert(i);
});
})(i);
}
This will make the three buttons pop up "0", "1", and "2" as expected.
The reason for this is that a closure keeps a reference to its enclosing stack frame, which holds the current values of its variables. If those variables change before the closure executes, then the closure will see only the latest values, not the values as they were at the time the closure was created. By wrapping the closure creation inside another function as in the second example above, the current value of the variable i is saved in the stack frame of the anonymous function.
This is considered a closure. It means the code contained will run within its own lexical scope. This means you can define new variables and functions and they won't collide with the namespace used in code outside of the closure.
var i = 0;
alert("The magic number is " + i);
(function() {
var i = 99;
alert("The magic number inside the closure is " + i);
})();
alert("The magic number is still " + i);
This will generate three popups, demonstrating that the i in the closure does not alter the pre-existing variable of the same name:
The magic number is 0
The magic number inside the closure is 99
The magic number is still 0
They are often used in jQuery plugins. As explained in the jQuery Plugins Authoring Guide all variables declared inside { } are private and are not visible to the outside which allows for better encapsulation.
As others have said, they both define anonymous functions that are invoked immediately. I generally wrap my JavaScript class declarations in this structure in order to create a static private scope for the class. I can then place constant data, static methods, event handlers, or anything else in that scope and it will only be visible to instances of the class:
// Declare a namespace object.
window.MyLibrary = {};
// Wrap class declaration to create a private static scope.
(function() {
var incrementingID = 0;
function somePrivateStaticMethod() {
// ...
}
// Declare the MyObject class under the MyLibrary namespace.
MyLibrary.MyObject = function() {
this.id = incrementingID++;
};
// ...MyObject's prototype declaration goes here, etc...
MyLibrary.MyObject.prototype = {
memberMethod: function() {
// Do some stuff
// Maybe call a static private method!
somePrivateStaticMethod();
}
};
})();
In this example, the MyObject class is assigned to the MyLibrary namespace, so it is accessible. incrementingID and somePrivateStaticMethod() are not directly accessible outside of the anonymous function scope.
That is basically to namespace your JavaScript code.
For example, you can place any variables or functions within there, and from the outside, they don't exist in that scope. So when you encapsulate everything in there, you don't have to worry about clashes.
The () at the end means to self invoke. You can also add an argument there that will become the argument of your anonymous function. I do this with jQuery often, and you can see why...
(function($) {
// Now I can use $, but it won't affect any other library like Prototype
})(jQuery);
Evan Trimboli covers the rest in his answer.
It's a self-invoking function. Kind of like shorthand for writing
function DoSomeStuff($)
{
}
DoSomeStuff(jQuery);
What the above code is doing is creating an anonymous function on line 1, and then calling it on line 3 with 0 arguments. This effectively encapsulates all functions and variables defined within that library, because all of the functions will be accessible only inside that anonymous function.
This is good practice, and the reasoning behind it is to avoid polluting the global namespace with variables and functions, which could be clobbered by other pieces of Javascript throughout the site.
To clarify how the function is called, consider the simple example:
If you have this single line of Javascript included, it will invoke automatically without explicitly calling it:
alert('hello');
So, take that idea, and apply it to this example:
(function() {
alert('hello')
//anything I define in here is scoped to this function only
}) (); //here, the anonymous function is invoked
The end result is similar, because the anonymous function is invoked just like the previous example.
Because the good code answers are already taken :) I'll throw in a suggestion to watch some John Resig videos video 1 , video 2 (inventor of jQuery & master at JavaScript).
Some really good insights and answers provided in the videos.
That is what I happened to be doing at the moment when I saw your question.
function(){ // some code here }
is the way to define an anonymous function in javascript. They can give you the ability to execute a function in the context of another function (where you might not have that ability otherwise).

Confusing Javascript class declaration

I have some third-party Javascript that has statements like this:
FOO = function() {
...functions() ...
return { hash }
}();
It is working as designed but I'm confused by it. Can anybody define what this structure is doing? Is it just a weird way to create a class?
This is a technique that uses closure. The idiom is well-known, but confusing when you first see it. FOO is defined as the object that the outermost function() returns. Notice the parenthesis at the end, which causes the function to evaluate and return { hash }.
The code is equivalent to
function bar() {
...functions() ...
return { hash }
};
FOO = bar();
So FOO is equal to { hash }. The advantage of this is that hash, whatever it is, has access to stuff defined inside the function(). Nobody else has access, so that stuff is essentially private.
Google 'Javascript closure' to learn more.
Js doesn't really have classes, per se, but "prototypes". This means that no two objects are ever of the same "type" in the normal type-safe sense, and you can dynamically add members to one instance while leaving the other unmolested. (which is what they have done).
Believe it or not, the syntax they have used is probably the most lucid, as it doesn't try to hide behind some C-style class syntax.
Doug Crockford's Javascript: The Good Parts is a quick read, and the best introduction to OOP in js that I've come across.
That's not actually a class, just an object. I'd recommend reading this: http://javascript.crockford.com/survey.html
Because JavaScript doesn't have block scope, your choice is (mostly) to have all variable reside in global or function scope. The author of your snippet wants to declare some local variables that he doesn't want to be in the global scope, so he declares an anonymous function and executes it immediately, returning the object he was trying to create. That way all the vars will be in the function's scope.
The parans at the end make this the Module Pattern, which is basically a way to have a single instance of an object(Singleton) while also using private variables and functions.
Since there's closures hash, if it's itself an object or function, will have access to all variables declared within that anonymous Singleton object.
You're missing an open parens, but it is basically a way of usually hiding information within an object i.e. a way of setting up private and privelaged methods.
For example
var foo = (function() {
/* function declarations */
return { /* expose only those functions you
want to expose in a returned object
*/
}
})();
Take a look at Papa Crockford's Private Members in JavaScript. This is basically the pattern you are seeing, but in a slightly different guise. The function declarations are wrapped in a self-invoking anonymous function - an anonymous function that is executed as soon as it's declared. Since the functions inside of it are scoped to the anonymous function, they will be unreachable after the anonymous function has executed unless they are exposed through a closure created by referencing them in the object returned from the execution of the anonymous function.
It's generally referred to as the Module Pattern.

Categories