Javascript explain this code please - javascript

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.

Related

variable definition in javascript

I have no idea how to describe my question .
(function(fn){
var able=123;
function tmp(){
fn()
};
tmp();
})(function(){alert(able)});
This snippet throws a Reference Error :able is not defined' .
Would you please explain how javascript get variables to me ?
The scope of the "fn" function is not the same as the "parent" function, you should pass the "able" argument when you call the fn function, and then istantiate it in the fn function itself, like this:
(function(fn){
var able=123;
function tmp(){
fn(able)
};
tmp();
})(function(able){alert(able)});
Functions create lexical closures at the time of their creation. This means that when your alert function is created, the able variable does not exist. Wrapping the execution of fn in a lexical closure that does know about able at a later moment does not affect the already created lexical closure of fn.
If you come up with a question that better explains what you are trying to do, we can propose how to properly use closures to express that idea.
java script support in function local and global scoping.
in this case the "able" is local function scope you can't access outside the function.
If you use var the variable will be declared in the local scope. If u just declare the variable without a var, it will be declared in the global scope
Your code could be rewritten like this using named functions:
var func1 = function(fn) {
var able=123;
function tmp(){
fn()
};
tmp();
}
var func2 = function() {
alert(able)
}
func1(func2);
I believe this way it is clear that the variable 'able' is defined inside 'func1' (more precisely in its local scope) and you are trying to access it inside 'func2' which is outside the scope of 'func1' so it can not "see" into this scope.
More information about scoping in JavaScript can be found here: What is the scope of variables in JavaScript?

Global variable inside anonymous self-executing js function still available outside?

I have these two javascript files:
test1.js:
(function() {
console.log(global_var_test2);
})();
test2.js:
(function() {
global_var_test2 = "test";
})();
Obviously if i use the var keyword in test2.js the global_var_test2 variable will not be available in test1.js..but i thought that when you were wrapping all your code in a file inside a self-executing anonymous functions that you created a separate scope so that variables that were created without the var keyword would still not be visible outside ? When running the code above im able to access global_var_test2 inside of test1.js.
If im remembering correct the use of a self-executing anonymous function is almost always used when writing javascript modules to isolate it from the other possibly installed modules you have..but that doesnt seem to work with the code above.. could someone explain why not ?
Your understanding is incorrect. If you assign to a variable without declaring it with var, you're creating a global variable, wrapper or no wrapper.
In "strict" mode, that would be an error. Therefore, if you really want to make sure you're not polluting the global environment — which is smart — you put your code in "strict" mode:
(function() {
"use strict";
// ... your code here
})();
If you accidentally forget var, you get an error. If you want a global variable, you can check for it:
if ("myGlobalSymbol" in window)
throw new Error("Something stole myGlobalSymbol from me!");
or whatever.
Variables created with var outside of a function are global - the same as if you had not used var.
Since you should be defining all of your variables via either var myvar or window.myvar = stuff, immediately invoked functions are used to prevent your var statements from polluting the global environment and potentially causing clashes.

The need for JS functions which are self executing?

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();
}
]
}

javascript anonymous function in variable

in the last few days i'm interesting in anonymous function in javascript , so i started to "explore" frameworks such as jquery , in the very first line i saw this piece of code :
var jQuery = (function() { .. functions .. }();
and a question came in mind - what is the purpose of that code?
why a variable contain anonymous function? what is the uses with that var? is it kind of function container or something? if it is how to access the functions?
what is the purpose of that code?
You are actually missing a closing parenthesis for this code to be valid javascript:
var jQuery = (function() { ... })();
It defines an anonymous function and executes it immediately storing the result of it in the variable.
You can think of it like this:
var jQuery = foo();
It's just that they didn't bother to define foo as an external function as they didn't need to call it elsewhere in the code. So they defined it as an anonymous function.
By doing this everything that is declared inside this anonymous function is scoped and accessible only to the containing anonymous function. It is not accessible to the outside.
By reducing scope for all contents of the function, you prevent possible collisions in the global scope, accidental hoisting, and minimize the additional attached objects to the window object.

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