Explain the following JavaScript statement? [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Why do you need to invoke an anonymous function on the same line?
(19 answers)
Closed 9 years ago.
var ninja = (function(){
function Ninja(){};
return new Ninja();
})();
Why is the function above encapsulated in parentheses and why is there a (); at the end?
I think it's a constructor function because of the (); at the end, but why is the object wrapped in parentheses?

This code is equivalent to:
function Ninja() {
// nothing here
}
var ninja = new Ninja();
Though in the code you listed, the function/object Ninja is not global scope.
The code (function() {...})(); basically says "take whatever function is contained inside here and execute it immediately". So it's creating an anonymous function and calling it right afterwards.

It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this keyword would change meaning, e.g. in
var someClass = function() {
this.property = something;
this.update = (function(obj) {
function() {
$('.el').each(function() {
$(this).html( obj.property );
});
};
)(this);
};
While I want to refer to this.property inside the $('.el').each(), this changes meaning within that scope and refers to the current DOM element that is being looped through with .each(). So by passing this as a parameter into the IIFE (and calling that parameter obj) I can use obj.property to refer to what is this.property when outside the scope of $('.el').each( ..., function() { ... });.
Let me know if that makes sense or if you have any questions :)

Why is the function declaration encapsulated in '('s and also why is
there a '();' in the end
Its declaring and executing the function at the same time.
You may see: Named function expressions demystified - by Juriy "kangax" Zaytsev

As suggested: Refering to Benalman
Immediately-Invoked Function Expression (IIFE)
Fortunately, the SyntaxError “fix” is simple. The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
// Either of the following two patterns can be used to immediately invoke
// a function expression, utilizing the function's execution context to
// create "privacy."
(function(){ /* code */ }()); // Crockford recommends this one
(function(){ /* code */ })(); // But this one works just as well

Related

how to use javascript functions? (defining functions in label)

There are different ways of defining the javascript functions. I often use the simplest way to define the function
function myfunc(){
}
and the next way to define the function in the variable like this (a little bit confusing the way of using)
var myvar = myfunc(){
/*some code*/
}
and the difficult way for me and mostly found in codes developed by advanced programmers like the following
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}
Please, can anyone clear my concept on this how can I use?
function myfunc(){}
Function declaration: the function is declared using the standard syntax
function functionName(params[]) {
//functionbody
}
Using this syntax declares the function at the begin of the scope execution, so they'll be available everywhere in their scope(and in their descendeant scopes).
var s = myfunc(); //s == 0
function myfunc() {return 0;}
var myfunc = function() {};
This uses the pattern known as function expression, it just assigns a reference of an anonymous function to a variable named myfunc. Using this syntax won't allow you to use the function until the variable is parsed. Even if variables are hoisted at the top of their scope, they're initialized when the interpreter parses them, so the above example won't work:
var s = myfunc(); //ReferenceError: myfunc is not defined
var myfunc = function() {return 0;};
But the example below will:
var myfunc = function() {return 0;};
var s = myfunc(); //s == 0
The third example is just assigning an anonymous function to an object property(also known as object method) in the way we've just done with function expression, so if I use the pattern above the code will become:
var onOpen = function() {},
onClose = function() {},
SqueezeBox = {//curly braces denotes an object literal
presets: {//again, this is a nested object literal
onOpen: onOpen,
onClose: onClose
}
};
This acts exactly the same as your example, with the only difference that here I used a variable to get a reference to the anonymous function before passing it to the object. If you need to know more about objects, I recommend you reading the MDN docs. Anyway, if you're really intrested in how JS works, I'd suggest Javascript Garden, which is a very good article about JS.
The first code snippet is a function declaration:
function myfunc() { }
You are declaring a named function called myfunc. You can verify this by myfunc.name === "myfunc"
Your second code snippet contains syntax error. I believe you meant:
var myvar = function() { };
This is an anonymous function expression assigned to a variable. You can verify this by typeof myvar === "function" and myvar.name === "".
The third snippet is a javascript object. Basically you can think of it as a Map or Dictionary<string, object>. So SqueezeBox contains 1 key presets, which in turn is a dictionary that contains 2 keys, onOpen and onClose, which both of them are anonymous functions.
In
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}}
He's creating an object SqueezeBox containing another object presets with two empty anonymous functions, he's defining the function inline with an empty body inside the {}.
A better way to see it is formatted this way:
var SqueezeBox={
presets:{
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
There is a lot of useful information on this subject here
Functions can have a name, which if specified cannot be changed. Functions can also be assigned to variables like any other object in javascript.
The first example is of a function declaration:
function myfunc(){
}
Using the function declaration you will be able to call the function from anywhere within the closure in which the function is declared, even if it is declared after it is used.
The other two examples are function expressions:
var myvar = function(){
/*some code*/
}
var SqueezeBox= {
presets: {
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
Using function expressions you are assigning functions to a variable. When doing this you must declare them before you use them. Most of the time you see this the functions will be anonymous but it is possible to name a function in an expression:
var myvar = function myFunc(){
myFunc(); // Because it has a name you can now call it recursively
}
When doing this, the myFunc function is only available within the body of the function because it is still a function expression rather than a declaration.
The third example declares a javascript object literal, SqueezeBox and within that object there is another called presets. Within this object there are two more objects/labels called onOpen and onClose. This means you can do the following to use these functions:
SqueezeBox.presets.onOpen();
SqueezeBox.presets.onClose();
You can think of onOpen and onClose as variables that are part of the object. So it's very similar to doing the following (but the variable is only in the scope of the presets object which is only available within the SqueezeBox object).
var onOpen = function() {};
This has already been answered here: What is the difference between a function expression vs declaration in Javascript?.
For the last example, as Atropo said, it's affecting an anonymous function to an object. It's similar to the var example.

Strange use of function within brackets [duplicate]

This question already has answers here:
How does the (function() {})() construct work and why do people use it?
(15 answers)
Closed 9 years ago.
Can someone explain to me what below code does, how it works and why it is used?
I don't understand why the function is within brackets or the brackets after the curly brackets.
(function () {
//Some javascript code...
}());
Thank you.
Edit/Follow up question:
Now that I better understand what above does, what effect would this have when used with jQuery:
$(document).ready(function () {
(function () {
//code here
}());
});
That is a self-executing function. It creates an anonymous function and immediately executes it.
It can be used for many purposes, such as creating a new scope.
var x = 10
(function () {
var x = 5
}())
alert(x) // 10
This is a self executing anonymous function.
First is the anonymous function:
(function(){
//Normal code goes here
})
The really interesting part is what happens when we add this right at the end:
();
Those brackets cause everything contained in the preceding parentheses to be executed immediately.
Javascript has function level scoping. All variables and functions defined within the anonymous function aren't available to the code outside of it, effectively using closure to seal itself from the outside world.
This design pattern is useful for modular Javascript.
You may read more here:
What is the purpose of a self executing function in javascript?
#doornob is correct. However, there is a syntax error in the original post. It should look like this:
(function() {
// your code goes here
})();
While this is commonly described as a "self-executing function", a more accurate term is "Immediately Invoked Function Expression." We can call that an "iffy." This is a type of closure.
This pattern is is commonly extended into something called the module pattern, which looks like this:
var myModule = (function() {
var my = {};
var privateFoo = 'I am foo. I am a private field!';
my.publicMethodGetFoo = function() {
return privateFoo;
}
return my;
}) ();
This is very much like a class in a traditional OOP language such as C++ or Java. The properties declared using the var keyword cannot be accessed outside of the module. Though there is no such thing as access modifiers in JavaScript, these properties are for all intents and purposes 'private'.
Note that we created an object called 'my'. This object is returned at the end of the module, which means it is exposed to the 'outside world.' Therefore it's accessible outside of the module. Any field or method that we add to 'my' will therefore be public.

What do these double parentheses do in JS? [duplicate]

This question already has answers here:
What do parentheses surrounding an object/function/class declaration mean? [duplicate]
(7 answers)
Closed 9 years ago.
I'm reading the book secrets of the js ninja, and very often I saw code like this
(function(){
something here;
})();
Why do we need to enclose the function within parentheses and why do we add one more pair of parentheses after that?
Its a self calling function, that invokes its self as the script finishes loading. You can call it without arguments, or you can add arguments to it such as window or document.
You use it in a way that jQuery use it:
(function( window, undefined ) {
// jQuery code
})(window);
An (almost) alternative syntax to do the same thing:
! function( window, undefined ){
// some code…
}(window);
Read more at: http://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/
This
(function(){
alert('hello');
})();
although it is a function is it called automatically so you dont/can't call it manually
These can be useful for for loops like so
This will fail because i would be equal to 9 after 5 seconds
for(var i = 0; i < 10; i++) {
window.setTimeout(function(){
console.log(i);
}, 5000)
}
So you could do this
for(var i = 0; i < 10; i++) {
(function(a){
window.setTimeout(function(){
console.log(a);
}, 5000)
})(i);
}
Also good for creating a "private" scope like this
(function(){
var test = 'hello';
console.log( test ); // 'hello'
}());
console.log( test ); // 'undefined'
The last set of parentheses causes the function to execute immediately. A function is created and executed without ever assigning it anywhere. The reason one might wrap their code in a function like this is to encapsulate code. Take this for example:
var myVar = 'whatever';
function shout() { alert(myVar); }
Here, myVar and shout have just become global variables. You can open up your console and type window.myVar or window.shout and you'll be able to access and change those variables. By wrapping it in a function, those variables remain local to the outer function:
(function() {
var myVar = 'whatever';
function shout() { alert(myVar); }
})();
window.myVar and window.shout are undefined. The only exist inside that function.
The pattern is also used to create a closure around local variables. See JavaScript closure inside loops – simple practical example.
Self invoking function, basically it calls itself stright away.
Used normally to pass in a variable like jQuery to insure that $ is truly the jQuery object!
(function($){
// $ now is equal to jQuery
})(jQuery);
It runs the function you just created. The reason to do this is that it encloses all of the code you write within a new scope. This means when you define vars and functions, they will be kept within the scope of that function() you just created.
In short, it encapsulates code.

Purpose of the outer extra parenthese on JavaScript closure function [duplicate]

This question already has answers here:
JavaScript - self-executing anonymous functions and callback
(2 answers)
Closed 9 years ago.
What is the purpose of the outer extra parentheses on the below JavaScript closure function? I have been told in other posts that they are not strictly necessary, but they're a convention to make it clear that the result of the function is being passed, not the function itself. The below quote from http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
, however, conflicts. Which is correct?
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());
I think that different engines have different ways of interpreting
function(){...}();
so the most popular and accepted way to make it clear, to all engines, is to group the code in parentheses.
(function(){...}());
At the same time, what you quoted makes a very interesting point. A function expression might go:
var f = function() {...}
Whereas a function declaration looks like:
function f() {...}
You see how it's easy/convenient for the parser to tell the difference by looking at the first token?
IF TOKEN1 EQ "function": FXN DECLARATION
ELSE: FXN EXPRESSION
But it wouldn't make sense for your (immediately-invoked) function to be a function declaration (it's not going to be re-used, you don't want to have it hoisted, or in the namespace, etc.) so adding some innocuous parentheses is a good way of indicating that it's a function expression.
First of all, I must clear up:
(function () {
}());
is equivalent for
(function () {
})();
and also for (Backbone.js uses it)
(function(){
}).call(this);
Second, if you're going to use it that way, then it's not an anonymous/closure function. its Immediately-Invoked Function expression
it would act as a closure (because it won't be immediately-invoked) if you assign its returned context to a variable. This kinda useful if you need a static class (when properties and methods could be accessed without instantiation). For example:
var stuff = (function(){
// AGAIN: its not an IIFE in this case
function foo() // <- public method
{
alert('Jeeez');
}
return {
foo : foo,
}
})();
stuff.foo(); //Alerts Jeeez
What is the purpose of the outer extra parentheses on the below
JavaScript closure function?
The purpose isn't usual and quite strange - its all about function arguments.
For example,
(function(window, document){ // <- you see this? 2 "arguments"
alert(arguments.length); // 0!
})();
but if we pass them to that outer parentheses
(function(/* So its not for arguments */ ){
alert(arguments.length); // 2
})(window, document); // <- Instead we pass arguments here
The extra surrounding parentheses disambiguate a function expression from a regular function declaration.
Though the extra parentheses are standard practice, the same thing can be achieved by doing this instead:
void function() {
// do stuff
}();
Or, even:
+function() {
// do stuff
}();
Though, out of these two alternatives, I prefer the void notation because in most cases we don't really care about the return value of an immediate invocation.
Other places where the parentheses aren't required is when an expression is expected:
setTimeout(function() {
return function() {
alert('hello');
}
}(), 1000);
They are necessary because the parser goes in the function declaration mode when it sees
function
in a statement context.
After function token, it is expecting a name for the function because a function declaration must include a name for the function. But instead of a name it sees ( instead, so it's a syntax error.
I think, it could backtrack and unambiguously just treat it as a function expression but it doesn't.
var module = XXX
In the above, XXX is in expression context, if a function appears there, it is treated as a start of a function expression. Function expressions don't have to have
a name for the function, so it's not a syntax error to have ( appear right after function.
So you can write:
var module = function(){}();
But not
function(){}()
You can use many tricks to make the above an expression:
(XXX)
!XXX
~XXX
+XXX
//This doesn't work however:
{YYY} //the braces are delimiting a block, and inside block you start in
//a statement context
XXX is in expression context because it's enclosed by parenthesis or is following a unary operator, therefore any function substituted for XXX is a function expression.

How does this function create an object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What do empty parentheses () after a function declaration do in javascript?
I understand basically how Javascript works. Now I'm self-learning Javascript design patterns by going through other programmers' works and
I come across this
var $a = (function() {
var a..... //assigning values & functions to variables
return { init : init }; //in the variable above there is "init"
})();
$a.init();
I can tell that $a.init() creates an object that has the properties & functions listed above. But I don't understand how it actually work.
Why is the function written this way(function() { })() ?
Why is return {init: init} necessary when there is already an init function above?
What kind of pattern is this?
This is the common module pattern.
This
var $a = (function() {
var a..... //assigning values & functions to variables
var init = function() {... uses a};
return { init : init }; //in the variable above there is "init"
})();
$a.init();
is about like doing
var a..... //assigning values & functions to variables
var $a = { init : function(){... uses a} }; //in the variable above there is "init"
$a.init();
but with the advantage that a is private (you can't read or write it if there is no function giving access to it) and doesn't encumber the global namespace. For the same reason, the locally declared init function must be declared in the returned object.
(function() {
})();
Is called a IIFE Immediately Invoked Function Expression. Basically it is a function which is executed immediately without explicitely calling it. The brackets enclosing the function are turning the declaration into an expression, and the empty () at the end are the parameters handed over to the IIFE.
$a is assigned the returnvalue of your IIFE, which is a object with a method called init, which invokes a function inside your IIFE which is also called init.
return { init : init };
/\ the name of the method which is called internally
/\ the name of the method which is returned from the function
It is a common way to modularize your Javascript and create a sort of privacy (which is not too trivial, because javascript per default has no privacy like other languages do).
This way, other parts of the javascript only have access to the properties your declare in your return statement, but not the internal stuff you declare in your IIFE.
the extra brackets mean, that this function is immediately invoked. which means everything inside is executed and the return value of that function will be the value of $a.
in your example $a contains now an object { init: init}
if you leave out the extra bracket you would should declare a new function which you could call.
read more about immediately invoked function expressions here

Categories

Resources