How does this function create an object [duplicate] - javascript

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

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.

Explain the following JavaScript statement? [duplicate]

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

Why is this function wrapped in parentheses, followed by parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 9 years ago.
I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?
(function() {
//stuff
})();
Why is this written like this? Why not just use stuff by itself and not in a function?
EDIT: i know this is defining an anonymous function and then calling it, but why?
This defines a function closure
This is used to create a function closure with private functionality and variables that aren't globally visible.
Consider the following code:
(function(){
var test = true;
})();
variable test is not visible anywhere else but within the function closure where it's defined.
What is a closure anyway?
Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.
Check this code and read comments along with it:
// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};
// closure part
(function(pubObj){
// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};
// add function to public object that accesses private functionality
pubObj.alertValues = closureFunc;
// mind the missing "var" which makes it a public variable
anotherPublic = 333;
})(publicObject);
// alert 111 & alert 222
publicObject.alertValues(publicVar);
// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"
Here's a JSFiddle running code that displays data as indicated by comments in the upper code.
What it actually does?
As you already know this
creates a function:
function() { ... }
and immediately executes it:
(func)();
this function may or may not accept additional parameters.
jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:
(function(paramName){ ... })(jQuery);
But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.
That construct is known as a self-executing anonymous function, which is actually not a very good name for it, here is what happens (and why the name is not a good one). This:
function abc() {
//stuff
}
Defines a function called abc, if we wanted an anonymous function (which is a very common pattern in javascript), it would be something along the lines of:
function() {
//stuff
}
But, if you have this you either need to associate it with a variable so you can call it (which would make it not-so-anonymous) or you need to execute it straight away. We can try to execute it straight away by doing this:
function() {
//stuff
}();
But this won't work as it will give you a syntax error. The reason you get a syntax error is as follows. When you create a function with a name (such as abc above), that name becomes a reference to a function expression, you can then execute the expression by putting () after the name e.g.: abc(). The act of declaring a function does not create an expression, the function declaration is infact a statement rather than an expression. Essentially, expression are executable and statements are not (as you may have guessed). So in order to execute an anonymous function you need to tell the parser that it is an expression rather than a statement. One way of doing this (not the only way, but it has become convention), is to wrap your anonymous function in a set of () and so you get your construct:
(function() {
//stuff
})();
An anonymous function which is immediately executed (you can see how the name of the construct is a little off since it's not really an anonymous function that executes itself but is rather an anonymous function that is executed straight away).
Ok, so why is all this useful, one reason is the fact that it lets you stop your code from polluting the global namespace. Because functions in javascript have their own scope any variable inside a function is not visible globally, so if we could somehow write all our code inside a function the global scope would be safe, well our self-executing anonymous function allows us to do just that. Let me borrow an example from John Resig's old book:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
All our variables and functions are written within our self-executing anonymous function, our code is executed in the first place because it is inside a self-executing anonymous function. And due to the fact that javascript allows closures, i.e. essentially allows functions to access variables that are defined in an outer function, we can pretty much write whatever code we like inside the self-executing anonymous function and everything will still work as expected.
But wait there is still more :). This construct allows us to solve a problem that sometimes occurs when using closures in javascript. I will once again let John Resig explain, I quote:
Remember that closures allow you to reference variables that exist
within the parent function. However, it does not provide the value of
the variable at the time it is created; it provides the last value of
the variable within the parent function. The most common issue under
which you’ll see this occur is during a for loop. There is one
variable being used as the iterator (e.g., i). Inside of the for loop,
new functions are being created that utilize the closure to reference
the iterator again. The problem is that by the time the new closured
functions are called, they will reference the last value of the
iterator (i.e., the last position in an array), not the value that you
would expect. Listing 2-16 shows an example of using anonymous
functions to induce scope, to create an instance where expected
closure is possible.
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = items[i];
// Bind a function to the element
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );
};
})();
}
Essentially what all of that means is this, people often write naive javascript code like this (this is the naive version of the loop from above):
for ( var i = 0; i < items.length; i++ ) {
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[i] );
};
}
The functions we create within the loop are closures, but unfortunately they will lock in the last value of i from the enclosing scope (in this case it will probably be 2 which is gonna cause trouble). What we likely want is for each function we create within the loop to lock in the value of i at the time we create it. This is where our self-executing anonymous function comes in, here is a similar but perhaps easier to understand way of rewriting that loop:
for ( var i = 0; i < items.length; i++ ) {
(function(index){
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[index] );
};
})(i);
}
Because we invoke our anonymous function on every iteration, the parameter we pass in is locked in to the value it was at the time it was passed in, so all the functions we create within the loop will work as expected.
There you go, two good reasons to use the self-executing anonymous function construct and why it actually works in the first place.
It's used to define an anonymous function and then call it. I haven't tried but my best guess for why there are parens around the block is because JavaScript needs them to understand the function call.
It's useful if you want to define a one-off function in place and then immediately call it. The difference between using the anonymous function and just writing the code out is scope. All the variables in the anonymous function will go out of scope when the function's over with (unless the vars are told otherwise, of course). This can be used to keep the global or enclosing namespace clean, to use less memory long-term, or to get some "privacy".
It is an "anonymous self executing function" or "immediately-invoked-function-expression". Nice explanation from Ben Alman here.
I use the pattern when creating namespaces
var APP = {};
(function(context){
})(APP);
Such a construct is useful when you want to make a closure - a construct helps create a private "room" for variables inaccessible from outside. See more in this chapter of "JavaScript: the good parts" book:
http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA37&lpg=PA37&dq=crockford+closure+called+immediately&source=bl&ots=HIlku8x4jL&sig=-T-T0jTmf7_p_6twzaCq5_5aj3A&hl=lv&ei=lSa5TaXeDMyRswa874nrAw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBUQ6AEwAA#v=onepage&q&f=false
In the example shown on top of page 38, you see that the variable "status" is hidden within a closure and cannot be accessed anyway else than calling the get_status() method.
I'm not sure if this question is answered already, so apologies if I'm just repeating stuff.
In JavaScript, only functions introduce new scope. By wrapping your code in an immediate function, all variables you define exist only in this or lower scope, but not in global scope.
So this is a good way to not pollute the global scope.
There should be only a few global variables. Remember that every global is a property of the window object, which already has a lot of properties by default. Introducing a new scope also avoids collisions with default properties of the window object.

Anonymous Member Pattern Export/Import Function

I'm a bit confused. What is the purpose of the parameters when you initiate an anonymous member pattern designated below:
(function (<ParameterA>) {
})(<ParameterB>);
I understand that Parameter A is used to designate the scope of the function is this true?
Is ParameterB where you export the function?
Finally, I often see script indicating the following:
})(jQuery || myfunc);
Does that mean they're exporting these or returning these objects? And what's the point of using the two pipes (||); It a field goal thing?
Thanks in advance. Looking forward to interesting discussion.
Parameter A does not designate the scope of the function. The function's position determines the scope of the function. ParameterB is not where you export the function. In fact, the way this is set up, there is no pointer to the function anywhere which makes it an "anonymous function." In other words, as is, the function itself is un-exportable. Usually when you talk about exporting things, you're talking about exporting variables that you defined inside anonymous functions. For example, here I am exporting the function my_inner_function from an anonymous function.
(function (<ParameterA>) {
// export this function here.
window.my_inner_function = function() {
...
};
})(<ParameterB>);
Usually, the point of anonymous functions is that you have all kinds of variables that you don't want to export because you don't want to possibly muck with other code.
(function (<ParameterA>) {
// convert could be defined somewhere else too, so to be on the safe side
// I will hide it here in my anonymous function so nobody else can
// reference it.
var convert = function() {
...
};
})(<ParameterB>);
This is particularly important when you compress your Javascript and get function names like a and b.
(function (<ParameterA>) {
// So compressed!
var a = function() {
...
};
})(<ParameterB>);
(function () {
// Another compressed thing! Good thing these are hidden within anonymous
// functions, otherwise they'd conflict!
var a = function() {
...
};
})();
Now this
(function (<ParameterA>) {
})(<ParameterB>);
is the same thing as
// Assume ParameterB is defined somewhere out there.
(function () {
var ParameterA = ParameterB;
})();
Which gives you an idea why you'd use the parameters. You may find the parameter approach less confusing, or you may want to make it clear that you don't want to affect "by value" variables such as numbers and strings.
As others have pointed out, a || b is spoken as "a or b" and means "a if a evaluates to true, otherwise b, no matter what b is."
Edit
To answer your question, when you get to })(); the () causes the anonymous function to run. Remember that Javascript engines will first parse all code to make sure the syntax is correct, but won't actually evaluate/execute any code until it reaches that code. Hence, it's when the anonymous function runs that var ParameterA = ParameterB; gets evaluated. Here are some examples that hopefully help.
var ParameterB = "hello";
(function () {
var ParameterA = ParameterB;
// alerts "hello" because when this line is evaluated ParameterB is still
// "hello"
alert(ParameterA);
})(); // () here causes our anonymous function to execute
ParameterB = "world";
Now in this example, the function is no longer anonymous because it has
a pointer. However, it acts the same as the previous example.
var ParameterB = "hello";
var myFunction = function () {
var ParameterA = ParameterB;
// alerts "hello" because when this line is evaluated ParameterB is still
// "hello"
alert(ParameterA);
};
myFunction();
ParameterB = "world";
In this example, I change the order of the last 2 lines and get different
results.
var ParameterB = "hello";
var myFunction = function () {
var ParameterA = ParameterB;
// alerts "world" because when this line is evaluated ParameterB has
// already changed.
alert(ParameterA);
};
// notice that I moved this line to occur earlier.
ParameterB = "world";
myFunction();
The code block above executes an anonymous function immediately after declaring it.
ParameterA is a parameter to the anonymous function you are declaring
ParameterB is the value you are passing to ParameterA
So the function you declared will be executed immediately, passing ParameterB as the value for ParameterA.
The jQuery || myFunc block means this: use jQuery as the argument unless it is not defined, in which case use myFunc.
Edit:
This is often used when defining jQuery plugins to avoid conflicts with the $ variable if multiple javascript libraries are being used. So you would make your plugin definition a function that accepts $ as a parameter, which you would execute immediately, passing jQuery as the value to $.
Example (from jQuery docs):
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
The result of the above code block will be a plugin definition where you are guaranteed that $ will be an alias for jQuery.
For parts 1 and 2, ParameterA could be used to alias a nested hierarchy. (ie: YAHOO.util.Event passed in as ParameterB, can be used as "e" in ParameterA.) That way, inside the anonymous function, you wouldn't be typing out the full namespace path. [I know you're a jquery guy, but the yahoo namespace is longer, and illustrates the point better :)] Alternatively, you could just manually store the reference in a var inside the function.
the jquery || myFunc syntax is shorthand for "use jquery if it is truthy/available, or myFunc if it is not".
It's sort of like var toUse = jQuery !== undefined ? jQuery : myFunc;
This is because javascript allows falsy value evaluation without converting the objects fully to a boolean. ie: undefined is falsy, "" is falsy, null is falsy.
The alternative can be used to detect if a method or property is even available with &&.
ie: var grandParent = person && person.parent && person.parent.parent;
This will only be defined if the person has a parent, and their parent has a parent. Any failure along the && leading up to the last statement will result in grandParent being undefined.
Lastly, the parens around the || shortcut syntax are basically executing the function immediately after the declaration, passing the evaluated value into the anonymous function.
ie: (function(a, b) { return a + b; })(2,3)
Will immediately execute and return 5. In practice, this anonymous function execution could be used with the module pattern to establish a set of public methods which use private functions that themselves do not appear in the page's namespace. This is more in depth than your original question, but you can check out this article for more information: http://yuiblog.com/blog/2007/06/12/module-pattern/
ParameterA is referencing the value passed in at ParameterB. This:
(function (<ParameterA>) {
})(<ParameterB>);
Is sort of the same as this:
function test(<ParameterA>) {
}
test(<ParameterB>);
The difference is that this way you are using a closure to not have conflicting functions in the global namespace.
For the second part: the || work sort of like param = jQuery ? jQuery : myFunc. It passes in jQuery if it is defined, or myFunc if it isn't.
With your first part:
(function (<ParameterA>) {
})(<ParameterB>);
This means that the variable known as ParameterB outside the function will be known as ParameterA inside the function. This is known as a self-executing function, because the function is called as soon as it is defined. It means that you can use ParameterA inside the function without overriding a variable that exists outside the function.
For instance:
(function($){
})(jQuery);
This means that you can have $ as, for instance, Mootools outside the function and as jQuery inside it.
With your second part:
})(jQuery || myfunc);
This calls the function passing the jQuery variable if it exists, and myfunc if it does not. I don't quite know why you'd do this...

Categories

Resources