I want to know about this javascript function pattern [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function
(function())()
this is used in many js library like jquery,YUi

Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module.
See: Js Pattern

I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:
f = function() { … }; // Define a function.
f(); // Call it.
The only difference is that it does so without requiring a variable.

It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).
It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.

You're immediately calling an anonymus function with a specific parameter.
An example:
(function(name){ alert(name); })('peter') This alerts "peter".
In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:
jQuery.noConflict() (function($){ var obj = $('<div/>', { id: 'someId' }); })(jQuery)

It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).
Take for instance these two snippets:
function foo() {
print 'foo';
}
(function() {
print 'foo';
})();
The first won't do anything until you call foo(); whereas the second will print 'foo' right away.

Related

what exacly is (function()).() [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 8 years ago.
I'm a beginner in programming and I just wonder about one thing. To be exact the syntax of (function(){...}).()
This question has been probably asked but as I don't know what it is and how to call it, I had very small luck finding anything about this topic.
I have been checking some scripts lately and I noticed that in some of them people use:
(function(){
...
}).(something) //
So far I'm guessing it's something like function which calls itself right away? How do we use it and what are the advantages of this. What do I put inside where 'something' is? also sometimes before it starts it also has $ sign.
Imagine a normal function:
function foo(){
...
}
Now let's call that function:
foo();
Instead of calling the function using its name, let's call it directly:
(function foo(){
...
})();
Since I don't use this function any where else, let's remove its name:
(function(){
...
})();
Want to pass a parameter to the function? Sure!
(function(something){
...
})(something);
Advantage of this? We have a scope!
(function(something){
var bar = 5; // Can't access this outside the function
})(something);
This allows you to define stuff outside of the global scope.
Your first example is an anonymous self-invoked function. So you are right, it calls itself straight away. If it had a name, that name would ONLY be visible inside those brackets (..).
The dollar-sign functions are short-hand for jQuery calls.
You are correct in that it a function that calls itself immediately, also called a self executing function.
The $ is just shorthand using jquery.
function(){} is declaring a function, while when we do
$(function() {}) it means we pass a function into another function $() as parameter, where this function will be executed by $() when the times met
it is much like
var a = function() { do something }
a();
will do something, in C# its like delegate, while in C++ it is like function pointer, in javascript it is made simple though where you can directly embed a function at the position where a parameter should be

Advanced JavaScript: Why is this function wrapped in parentheses? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the (function() { } )() construct in JavaScript?
I came across this bit of JavaScript code, but I have no idea what to make out of it. Why do I get "1" when I run this code? What is this strange little appendix of (1) and why is the function wrapped in parentheses?
(function(x){
delete x;
return x;
})(1);
There are a few things going on here. First is the immediately invoked function expression (IIFE) pattern:
(function() {
// Some code
})();
This provides a way to execute some JavaScript code in its own scope. It's usually used so that any variables created within the function won't affect the global scope. You could use this instead:
function foo() {
// Some code
}
foo();
But this requires giving a name to the function, which is not always necessary. Using a named function also means at some future point the function could be called again which might not be desirable. By using an anonymous function in this manner you ensure it's only executed once.
This syntax is invalid:
function() {
// Some code
}();
Because you have to wrap the function in parentheses in order to make it parse as an expression. More information is here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
So to recap quickly on the IIFE pattern:
(function() {
// Some code
})();
Allows 'some code' to be executed immediately, as if it was just written inline, but also within its own scope so as not to affect the global namespace (and thus potentially interfere with or be interfered with by, other scripts).
You can pass arguments to your function just as you would a normal function, for example,
(function(x) {
// Some code
})(1);
So we're passing the value '1' as the first argument to the function, which receives it as a locally scoped variable, named x.
Secondly, you have the guts of the function code itself:
delete x;
return x;
The delete operator will remove properties from objects. It doesn't delete variables. So;
var foo = {'bar':4, 'baz':5};
delete foo.bar;
console.log(foo);
Results in this being logged:
{'baz':5}
Whereas,
var foo = 4;
delete foo;
console.log(foo);
will log the value 4, because foo is a variable not a property and so it can't be deleted.
Many people assume that delete can delete variables, because of the way autoglobals work. If you assign to a variable without declaring it first, it will not actually become a variable, but a property on the global object:
bar = 4; // Note the lack of 'var'. Bad practice! Don't ever do this!
delete bar;
console.log(bar); // Error - bar is not defined.
This time the delete works, because you're not deleting a variable, but a property on the global object. In effect, the previous snippet is equivalent to this:
window.bar = 4;
delete window.bar;
console.log(window.bar);
And now you can see how it's analogous to the foo object example and not the foo variable example.
It means you created an anonymous function, and call it with parameter 1.
It is just the same as:
function foo(x) {
delete x;
return x;
}
foo(1);
The reason that you still get 1 returned is that the delete keyword is for removing properties of objects. The rest is as others have commented, anything wrapped in brackets executes as a function, and the second set of brackets are the arguments passed to that block.
Here's the MDN reference for delete, and the MDN reference for closures, which discusses also anonymous functions.
People normally call these "Immediately Invoked Function Expressions" or "Self Executing Functions".
The point of doing this is that variables declared inside that function do not leak to the outside.

What happens when you put a function in parentheses? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I see functions inside parentheses in jQuery plugins and the like.
For example,
(function(args) {
// ...
})(localVariable);
What does this do, exactly?
You mean something like the following?:
(function() {
// ...
})();
This basically ensures that any "var" declarations are kept private (they are scoped to the anonymous function in which they have been placed) rather than global. For example, consider:
var counter = 0;
window['inc'] = function() {
return counter++;
};
vs.
(function() {
var counter = 0;
window['inc'] = function() {
return counter++;
};
})();
Both of these have the effect of defining a function window.inc that returns a counter that gets incremented; however, in the first version, counter is actually visible to all other modules, because it is in the global scope, whereas the latter ensures that only window.inc can access counter.
Note that the code creates a function and immediately invokes it (that's what the last parens are for).
The unofficial name is an 'immediate function' - the basic idea is that the function is defined and called on the fly.
Here's a simple example:
http://javascriptmountain.com/2011/06/functions/immediate-functions-in-javascript-the-basics/
The parentheses are actually not necessary unless the return value of the function is assigned to a variable, but they are usually used for readability.
The reason it is done in situations like jquery plugins is that it provides a sort of 'sandbox' for executing code. Say we did the following:
(function($) {
// augment $ with methods
}(jQuery));
this defines a function that takes in one parameter, then IMMEDIATELY calls the function, passing in the global jquery object. Any vars that are declared and used inside the immediate function will be locally scoped to the function, and will not interfere with global scope or disrupt any global variables that may have been declared in other pieces of javascript code being used (important for libraries intended to be used with large amounts of other code).
However, since we are passing in the global jquery object when we call the function, we can still add methods and properties to the '$' parameter inside of the function that will hang around on the jquery object after the function completes.
Hope this helps!

Javascript: Calling a function written in an anonymous function from String with the function's names withoout eval?

Update2:
What I really wanted to ask was already argued in a different page. Please check the following entry. (Thanks to BobS.)
How can I access local scope dynamically in javascript?
Hello.
I've started using jQuery and am wondering how to call functions in an anonymous function dynamically from String.
Let's say for instance, I have the following functions:
function foo() {
// Being in the global namespace,
// this function can be called with window['foo']()
alert("foo");
}
jQuery(document).ready(function(){
function bar() {
// How can this function be called
// by using a String of the function's name 'bar'??
alert("bar");
}
// I want to call the function bar here from String with the name 'bar'
}
I've been trying to figure out what could be the counterpart of 'window', which can call functions from the global namespace such as window["foo"].
In the small example above, how can I call the function bar from a String "bar"?
Thank you for your help.
Update:
Here's what I want:
Define functions that are only used in the closure.
Avoid creating an Object in the closure that holds those functions in order to be accessed as obj['bar'].
Avoid eval (if possible) in order to write code more simply in a straightforward manner (if exists).
Decide function's name dynamically via the URI parameter or anything variable.
Being a newbie of Javascript, I thought 'this' would be the counterpart of 'window' in the closure, and tried writing:
// in the closure
name = 'bar';
this[name]; // undefined ...
and failed (of course...).
All of these are for pursuit of further laziness. Javascript is kind of new to me and currently I've been trying to write code as lazy as possible.
As Kobi wrote, eval might be a good option. Alternatively, is there any reason not to do
$(function(){
var localNamespace = {};
function bar() {
alert("bar");
}
localNamespace['bar'] = bar;
// Now bar() can be called by, well, localNamespace['bar']
}
Update:
Similar SO entries, such as How can I access local scope dynamically in javascript?, seem to indicate you're out of luck without using one of these two approaches or something even uglier.
Inside your ready function:
window.bar = function bar() {
// ...
}
Then, you can access window['bar'].

Need help understanding a javascript function

I'm hoping someone can explain the following usage of JavaScript.
I have a page with a script that looks like this:
(function($){
// code
// and stuff
})(jQuery);
I'm trying to understand what this code does, specifically:
The opening parenthesis at the start
The usage of the $ symbol
The jQuery in parentheses at the end
thanks!
This is an anonymous function.
The specific example you provide is usually used when jQuery (which uses the "$") is conflicting with another library (prototype also uses "$").
What this does is say that whenever "$" is used within the function, it is to reference the jQuery object.
Normal:
$("foo").doStuff()
Conflict avoidance:
jQuery("foo").doStuff()
Using anonymous function to avoid conflict:
(function($){
$("foo").doStuff();
})(jQuery)
At the highest level, it is declaring a function and invoking it in the same statement.
Let's break it down into component parts:
First, we can use $ as an argument/variable name in a function, just like anything else:
function foo($)
{
alert($);
}
foo('hi'); //alerts 'hi'
Second, we can assign a function to a variable:
var foo = function($) {
alert($);
}
foo('hi'); //alerts 'hi'
Finally, we don't have to give functions names - we can just declare them. We wrap them in parenthesis to encapsulate the entire function declaration as a var, which we then call (just like above):
(function($) {
alert($);
})('hi');
In your case, jQuery is some object being passed into the function as the $ parameter. Probably the jQuery library root object, so you can call functions on it.
The parenthesis wrap the anonymous function so it can be called right away with the parameter being a reference to jQuery
$ is a valid variable name in JavaScript, so many frameworks use it for brevity. By including it here as the function argument, you're saying that you want to use $ as an alias for jQuery. This lets you keep your code as short as possible and save your user's bandwidth.
Answered in the first part - you're sending a reference to the jQuery object/framework to your anonymous function.
Briefly:
This declares an anonymous function which accepts one argument, referred to by the local variable name of $, and then immediately calls the function passing as the first argument the jQuery object.
Less briefly:
In javascript a function is declared like this:
function foo(arg1, arg2){
}
Later the function foo can be called:
foo("arg 1", "arg 2");
But in javascript functions are first class citizens; you may, if you choose, store a function in a variable. When doing this the variable name is the function name, so you write it like this:
var foo = function(arg1, arg2){
};
The trailing semicolon is required because a variable declaration (and assignment) is a statement. Later, the function foo can be called:
foo("arg 1", "arg 2");
The advantage here is that you can pass the function to another function, or store it in an array, or whatever. Functions of this sort are called anonymous functions (because they have no function name as such).
Inside the anonymous function foo, as seen above, you can declare local variables which remain withing the scope of that function and do not exist in the scope in which the function was declared. For example, the local arg1 and arg2 variables don't exist in the scope of the variable foo (but they do exist within the anonymous function stored in foo).
This trick allows us to create a private block in which we control what things are named without worrying about stomping over someone else's namespace.
You could write the example you provided as follows:
var foo = function($){
};
fn(jQuery);
Which is the same thing, but has that ugly intermediate variable. What may not be obvious is that the declaration of the anonymous function "returns" a function reference which can be invoked later... or at the same time, merely by adding the function call syntax of ().
What the code is doing is defining an anonymous function, which creates a private scope, and then immediately calling it without storing in a variable. Like this:
function(arg1){
}("arg 1");
I am not entirely sure why there's an extra set of parentheses arroudn the anonymous function definition, but they at least make the code a little more readable/logical. You are merely passing an argument to the result of the parenthetical expression, which happens to be a function:
(function(arg1){
})("arg 1");
All of tis allows jQuery to have a globally-scoped variable named jQuery, but also allows you the user to use the shorthand of $ without conflicting with other javascript frameworks which use the same name for other things.
Let’s first look at the inner function declaration:
function($){
// code
// and stuff
}
This is an anonymouse function declaration with one parameter named $. That function is then wrapped in parenthesis and called by appending (jQuery) to it with jQuery as parameter.

Categories