Why Self-Executing Anonymous Functions - javascript

Today I came a cross the self executing functions, than somehow I ended up knowing about
Self-Executing Anonymous Functions, then I've read this article: http://briancrescimanno.com/how-self-executing-anonymous-functions-work/
The thing is that I don't know WHY to use Self-Executing Anonymous Functions because if I need to do something like:
var test = "a";
(function(foo) {
alert(foo);
})(test);
I could just make something like:
var test = "a";
alert(foo);
Or did I miss anything?
also this can be done to any code inside the function, but I used alert() to make simple
Update:
Even thought I've already accepted and answer I would like to share something I've found, if anyone came across this question later :)
Using this notation we can also make an endless loop like following:
(function loop(){
// do something here
loop();
)();

There are a couple of reasons why one would use an IIFE:
1) No littering
var a = 'foo';
alert(a);
vs
(function() {
var a = 'foo';
alert(a);
}())
Both examples do the same thing, but in the second example there is no a variable inside the outer scope.
2) State capturing
var a = 'foo';
window.setTimeout(function() { alert(a); }, 1);
a = 'bar';
vs
var a = 'foo';
window.setTimeout( (function(a_copy) {
return function() { alert(a_copy); }
}(a)), 1);
a = 'bar';
The first example alerts bar, while the second alerts foo. You will find this technique used especially with loops.

Your initial example isn't worth to be executed in an anonymous function, so its a bad example to understand WHY to use this technique. Here is a good example to explore state capturing:
var list = [{id: 1, data: null}, ...];
for (var i = 0; i < list.length; i++) {
(function(item) {
// start async request, for each item in the list, in the order of the list
asyncAjax("get-data-from-somewhere.json?what=" + list[i].id, function (response) {
// thats the on success callback, which gets executed when the server responded
// each item will have different response times, therefore the order of response is various
// if we would use simply list[i].data, it wouldn't work correctly, because "i" would has the value of list.length, because the iteration has been finished yet.
item.data = response;
});
})(list[i]); // the function will preserve the reference to the list item inside, until the function has been fully executed
}
When writing sync. code, you can always fallback to classic object oriented style of structering your code. So you can avoid closures / instant-anonymous function calls. But as soon as you use async. mechanics, closures get very handy and make your code looking more clean, off course only if you can read and understand closures :)
By the way, you could also simply write:
function(private) {}(outer)
is the same as
(function(private) {})(outer)
but the second is better, because its simply more obvious for the reader.

The syntax you describe is commonly referred to as an "immediately invoked function expression", or IIFE.
One of the common use cases is to emulate private variables:
var ns = (function () {
var x = 1; // "private"
return {
getX: function () {
return x;
}
}
}());
ns.getX(); // 1
ns.x; // undefined because x is "private"
In that example the x variable is local to the IIFE. It's not directly accessible outside of it. However, since it is referred to by the getX method, which is accessible outside of the IIFE (because it's part of the returned object) a reference to x is kept alive. This is what is usually meant by the term "closure".

Self executing functions are not really useful if you just do an alert inside.
Consider something like this:
(function(foo) {
var a = ..
// do something with a and foo
})(test);
The advantage here is that a is "private" inside the method and cannot be used outside the method. So a doesn't end up as a global variable and can't be overwritten by some other piece of javascript which uses a variable of the same name.

Related

assign a function into a variable and run itself

I have read a interested blog where this above technique is applied, i understand it will run the function itself. but what's the purpose assign to a variable, when i try to console.log the variable i get undefiend.
var test1 = (function(){
console.log('yay')
})();
console.log(test1)
what's the differnet doing this way below
(function test1(){
console.log('yay');
})();
Suggestion are appreciated. :)
The immediately invoked function expression (IIFE) in Javascript serves to introduce a closure via a new scope. This is often done to compensate for the lack of block scoping in Javascript or provide information hiding a la module pattern (seen often in jQuery plugins).
Minimal example below:
var counter = (function() {
var i = 0;
function inc() {
i++;
return i;
}
return inc;
})();
The return exposes assigns the function inc to the variable counter. Successive invocations of counter() will result in 1, 2, etc. while keeping i hidden.
This is roughly equivalent to an object oriented approach that declared i as private.
In your sample above the function is void which makes no sense to assign the function result to a variable since it is returning nothing:
However tweaking your sample a little bit:
var test1 = (function(){
console.log('yay'); return "hello";
})();
then it makes sense since test1 will return "hello".
So in your original sample there are not differences and the fact that you assign a the result of a function which is not returning values is a bit odd.

JavaScript anonymous function expression vs IIFE

Encountered some code that's using IIFEs in an expression rather than just a normal function.
var custom_type = (function() {
return $('#myDiv').attr('custom_type');
})();
Normally I would write this as something like:
var custom_type = function() {
return $('#myDiv').attr('custom_type');
};
What's the reason for the IIFE? The only thing I can think of is that the IIFE might assign the custom_type variable only once at the beginning whereas the second might continue to check for the updated type every time the variable is referenced.
In this example, you can dispense with the function altogether and just do:
var custom_type = $('#myDiv').attr('custom_type');
However in general you can use an IIFE for more complex "just-in-time" computation of variable assignments - I like to use them if I need to iterate over something, so I can have i without polluting the current scope.
In your second example, though, the result is completely different - you will need to call the function custom_type() to get the current value, whereas the first piece of code will get its value once, and the variable will hold that value.
The IIFE will actually run (immediately-invoked function expression), so the variable will be set to its response.
Here's a JSFiddle to demonstrate this, watch your JS console for the output: http://jsfiddle.net/Y4JmT/1/
Code Here:
var custom_type = (function() {
return 'foo';
})();
var custom_type2 = function() {
return 'bar';
};
console.log('iife = ' + custom_type);
console.log('non-iife = ' + custom_type2);
In your JS console you'll see something similar to:
iife = foo
and
non-iife = function () {
return 'bar';
}
The first one of yours (IIFE) executes the function and store its result, the seconds stores function as definition.
(function(x) {
return x * 2;
})(5);
You are making a call like to normal funciton: func(arg1, arg2), but instead of function name you pass whole function definition, so the above would return 10 like:
function multiply(x) {
return x * 2;
}
multiply(5);
They mean the same thing, you are making calls. Unlikely the first, second is definition plus a call.
IIFEs allow you to invoke a function (anonymous or otherwise) at the point of creation.
Have you looked at this?
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

When will I need a javascript anonymous function immediately invoked?

I see no situation where I need this
(function(param){
alert(param);
//do something
})("derp");
istead of this
alert("derp");
//do something
EDIT: ok, thanks everybody, i think i got it.
so if you have this:
var param = "x";
var heya = "y";
(function(param){
alert(param);
//do something
})(heya);
the global variable "param" will be ignored in the scope of the anonymous function?
How about this scenario?
Example #1 - Uses an Immediately Invoked Function Expression that closes over a single variable and returns another function. Resulting in a beautiful, encapulated function.
var tick = (function () {
//Example of function expression + closure
var tock = 0;
return function() {
return ++tock;
}
}());
//It is impossible to alter `tock` other than using tick()
tick(); //1
tick(); //2
tick(); //3
tick(); //4
VERSUS
Example #2 - Uses a Function Declaration w/ a global variable
//Unnecssary global (unless wrapped in another function, such as jQuery's ready function)
var tock = 0;
function tick() {
return ++tock;
}
tick(); //1
tock = 4; //tock is exposed... and can be manipulated
tick(); //5
tock = 6;
tick(); //7
It is a contrived example but still a real case scenario in situations where people may want to generate consecutive UNIQUE ID's with no possibility of collision.
Well, you don't - for this simple example.
In JavaScript, variables are scoped to functions; therefore, if you wrap it in a function, you avoid global namespace pollution.
Well, in the example you've given, no, there probably isn't any reason why you would do this.
However, such a pattern is used typically to ensure that variables or functions, you require at a global level
Can be isolated from others potentially defined in other libraries
thus is an effective way to hide private variables
Can be protected against being tampered with by other libraries
Globals in Javascript are evil.
In particular, when working with jQuery I will frequently enclose the $(callback(){}) in a function like this, so that I can have global state for the jQuery code that I don't want inside the callback itself, usually because I have other code that isn't necessarily dependant on the jQuery ready initialisation:
function(){
var something = 'something';
$(function(){
something = 'jQuery bound';
});
}();
Aside from polluting the global namespace, memory usage is the other reason to do this - if you're pulling in a big data structure that only gets used once, wrapping that in a (function(){})() block means that you know it will be cleaned up once the function is finished executing.

Difference between these two types of self executing function on JavaScript

I always use the following self executing function in order to avoid exposing my code to global scope in JavaScript:
(function() {
//Code comes here
})();
I believe that this is also called self executing anonymous function as well. Sometimes, I also see the below code used for the same purpose:
(function(d){
//Code comes here
})(document.documentElement);
I am not sure what makes the difference here so I am asking this question.
What is the difference (or are the differences) between these two types of self executing function on JavaScript?
The code below demonstrates what's happening. In reality, the foo and bar variables don't exist, and the functions are anonymous.
var foo = function() {}
foo();
var bar = function(d){}
bar(document.documentElement);
The (function(d){})(d) method is called a closure. It's used to pass variable values which are subject to change, such as in loops.
Have a look at a practical an example:
for(var i=0; i<10; i++) {
document.links[i].onclick = function(){
alert(i); //Will always alert 9
}
}
After implementing the closure:
for(var i=0; i<10; i++) {
(function(i){
document.links[i].onclick = function(){
alert(i); //Will alert 0, 1, ... 9
}
})(i);
}
Remember that function arguments and variables are the same thing, deep down.
The second example is (basically) just shorthand for
(function(){
var d = document.documentElement;
}());
since it avoids the need for the var and the =.
There are some common uses for this pattern:
Creating lexically scoped variables (just remembered this after seeing Rob's answer...)
//this does not work because JS only has function scope.
// The i is shared so all the onclicks log N instead of the correct values
for(var i = 0; i< N; i++){
elems[i].onclick = function(){ console.log(i); }
}
//Each iteration now gets its own i variable in its own function
// so things work fine.
for(var i=0; i<N; i++){
(function(i){
elems[i].onclick = function{ console.log(i); };
}(i));
}
In this case, passing the parameters directly allows us to reuse the same variable name inside, in a way that var i = i would not be able to. Also, the conciseness is a benefit, since this is just a boilerplate pattern that we don't want to dominate over the important code around it.
It makes it easy to convert some old code without having to think too much about it
(function($){
//lots of code that expected $ to be a global...
}(jQuery)) //and now we can seamlessly do $=jQuery instead.
Parameters that are not passed are set to undefined. This is useful since normally undefined is just a global variable that can be set to different values (this is specially important if you are writing a library that needs to work w/ arbitrary third party scripts)
(function(undefined){
//...
}())
The first function takes no parameters. The second one takes a single parameter. Inside the function, the parameter is d. d is set to document.documentElement when the function is called.
It looks like the author of the second code wants to use d as a shorter way to write document.documentElement inside the function.
if you want to pass arguments to the self executing anonymous functions, use the second one. It might come in handy when you want to use variables in the function that have the same name with others in the global scope :
var a = "I'm outside the function scope",
b = 13;
alert(a);
alert(b);
(function(a,b){
// a is different from the initial a
alert(a);
// same goes for b
alert(b);
})("I'm inside the function scope",Math.PI);
It can also be useful to use something like :
var a;
console.log(a === undefined); // true
undefined = true;
console.log(a === undefined); // false
(function(undefined){
console.log(a === undefined); // true, no matter what value the variable "undefined" has assigned in the global scope
})();
when trying to implement the null object design pattern
If you are concerned about efficiency, you might end up using something like this :
var a = 2;
(function(window){
alert(a);
// accessing a from the global scope gets translated
// to something like window.a, which is faster in this particular case
// because we have the window object in the function scope
})(window);
One reason for using the second form, with the argument, is that insulates your code against other js code loaded later on the page (eg other libraries or framework code) that might re-define the variable passed in as the argument.
One common example would be if the code within your self-executing anonymous function relies upon jQuery and wants to use the $ variable.
Other js frameworks also define the $ variable. If you code your function as:
(function($){
//Code comes here
})(jQuery);
Then you can safely use $ for jQuery even if you load some other library that defines $.
I have seen this used defensively with people passing in all the 'global' variables they need inside their block, such as window, document, jQuery/$ etc.
Better safe than sorry, especially if you use a lot of 3rd party widgets and plugins.
Update:
As others have pointed out the set of parentheses around the function are a closure. They are not strictly neccessary a lot of times where this pattern is used (#Rob W gives a good example where they're essential) but say you have a very long function body... the outer parentheses say to others reading the code that the function is probably self-executing.
Best explanation I saw of this pattern is in Paul Irish's video here: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/ starting about 1:30
This SO question also has some informative answers: How do you explain this structure in JavaScript?

Trouble using 'eval' to define a toplevel function when called from within an object

I've written (in JavaScript) an interactive read-eval-print-loop that is encapsulated
within an object. However, I recently noticed that toplevel function definitions specified to the interpreter do not appear to be 'remembered' by the interpreter. After some diagnostic work, I've reduced the core problem to this:
var evaler = {
eval: function (str)
{
return eval(str);
},
};
eval("function t1() { return 1; }"); // GOOD
evaler.eval("function t2() { return 2; }"); // FAIL
At this point, I am hoping that the following two statements wil work as expected:
print(t1()); // => Results in 1 (This works)
print(t2()); // => Results in 2 (this fails with an error that t2 is undefined.)
What I get instead is the expected value for the t1 line, and the t2 line fails with an error that t2 is unbound.
IOW: After running this script, I have a definition for t1, and no defintion for t2. The act of calling eval from within evaler is sufficiently different from the toplevel call that the global definition does not get recorded. What does happen is that the call to
evaler.eval returns a function object, so I'm presuming that t2 is being defined and stored in some other set of bindings that I don't have access to. (It's not defined as a member in evaler.)
Is there any easy fix for this? I've tried all sorts of fixes, and haven't stumbled upon one that works. (Most of what I've done has centered around putting the call to eval in an anonymous function, and altering the way that's called, chainging __parent__, etc.)
Any thoughts on how to fix this?
Here's the result of a bit more investigation:
tl;dr: Rhino adds an intermediate scope to the scope chain when calling a method on an instance. t2 is being defined in this intermediate scope, which is immediately discarded. #Matt: Your 'hacky' approach might well be the best way to solve this.
I'm still doing some work on the root cause, but thanks to some quality time with jdb, I now have more understanding of what's happening. As has been discussed, a function statement like function t1() { return 42; } does two things.
It creates an anonymous instance of a function object, like you'd get with the expression function() { return 42; }
It binds that anonymous function to the current top scope with the name t1.
My initial question is about why I'm not seeing the second of these things happen when I call eval from within a method of an object.
The code that actually performs the binding in Rhino appears to be in the function org.mozilla.javascript.ScriptRuntime.initFunction.
if (type == FunctionNode.FUNCTION_STATEMENT) {
....
scope.put(name, scope, function);
For the t1 case above, scope is what I've set to be my top-level scope. This is where I want my toplevel functions defined, so this is an expected result:
main[1] print function.getFunctionName()
function.getFunctionName() = "t1"
main[1] print scope
scope = "com.me.testprogram.Main#24148662"
However, in the t2 case, scope is something else entirely:
main[1] print function.getFunctionName()
function.getFunctionName() = "t2"
main[1] print scope
scope = "org.mozilla.javascript.NativeCall#23abcc03"
And it's the parent scope of this NativeCall that is my expected toplevel scope:
main[1] print scope.getParentScope()
scope.getParentScope() = "com.me.testprogram.Main#24148662"
This is more or less what I was afraid of when I wrote this above: " In the direct eval case, t2 is being bound in the global environment. In the evaler case, it's being bound 'elsewhere'" In this case, 'elsewhere' turns out to be the instance of NativeCall... the t2 function gets created, bound to a t2 variable in the NativeCall, and the NativeCall goes away when the call to evaler.eval returns.
And this is where things get a bit fuzzy... I haven't done as much analysis as I'd like, but my current working theory is that the NativeCall scope is needed to ensure that this points to evaler when execution in the call to evaler.eval. (Backing up the stack frame a bit, the NativeCall gets added to the scope chain by Interpreter.initFrame when the function 'needs activation' and has a non-zero function type. I'm assuming that these things are true for simple function invocations only, but haven't traced upstream enough to know for sure. Maybe tomorrow.)
Your code actually is not failing at all. The eval is returning a function which you never invoke.
print(evaler.eval("function t2() { return 2; }")()); // prints 2
To spell it out a bit more:
x = evaler.eval("function t2() { return 2; }"); // this returns a function
y = x(); // this invokes it, and saves the return value
print(y); // this prints the result
EDIT
In response to:
Is there another way to create an interactive read-eval-print-loop than to use eval?
Since you're using Rhino.. I guess you could call Rhino with a java Process object to read a file with js?
Let's say I have this file:
test.js
function tf2() {
return 2;
}
print(tf2());
Then I could run this code, which calls Rhino to evaluate that file:
process = java.lang.Runtime.getRuntime().exec('java -jar js.jar test.js');
result = java.io.BufferedReader(java.io.InputStreamReader(process.getInputStream()));
print(result.readLine()); // prints 2, believe it or not
So you could take this a step further by WRITING some code to eval to a file, THEN calling the above code ...
Yes, it's ridiculous.
The problem you are running into is that JavaScript uses function level scoping.
When you call eval() from within the eval function you have defined, it is probably creating the function t2() in the scope of that eval: function(str) {} function.
You could use evaler.eval('global.t2 = function() { return 2; }'); t2();
You could also do something like this though:
t2 = evaler.eval("function t2() { return 2; }");
t2();
Or....
var someFunc = evaler.eval("function t2() { return 2; }");
// if we got a "named" function, lets drop it into our namespace:
if (someFunc.name) this[someFunc.name] = someFunc;
// now lets try calling it?
t2();
// returns 2
Even one step further:
var evaler = (function(global){
return {
eval: function (str)
{
var ret = eval(str);
if (ret.name) global[ret.name] = ret;
return ret;
}
};
})(this);
evaler.eval('function t2() { return 2; }');
t2(); // returns 2
With the DOM you could get around this function-level scoping issue by injecting "root level" script code instead of using eval(). You would create a <script> tag, set its text to the code you want to evaluate, and append it to the DOM somewhere.
Is it possible that your function name "eval" is colliding with the eval function itself? Try this:
var evaler = {
evalit: function (str)
{
return window.eval(str);
},
};
eval("function t1() { return 1; }");
evaler.evalit("function t2() { return 2; }");
Edit
I modified to use #Matt's suggestion and tested. This works as intended.
Is it good? I frown on eval, personally. But it works.
I think this statement:
evaler.eval("function t2() { return 2; }");
does not declare function t2, it just returns Function object (it's not function declaration, it's function operator), as it's used inside an expression.
As evaluation happens inside function, scope of newly created function is limited to evaler.eval scope (i.e. you can use t2 function only from evaler.eval function):
js> function foo () {
eval ("function baz() { return 'baz'; }");
print (baz);
}
js> foo ();
function baz() {
return "baz";
}
js> print(baz);
typein:36: ReferenceError: baz is not defined
https://dev.mozilla.jp/localmdc/developer.mozilla.org/en/core_javascript_1.5_reference/operators/special_operators/function_operator.html
https://dev.mozilla.jp/localmdc/developer.mozilla.org/en/core_javascript_1.5_reference/statements/function.html
I got this answer from the Rhino mailing list, and it appears to work.
var window = this;
var evaler = {
eval : function (str) {
eval.call(window, str);
}
};
The key is that call explicitly sets this, and this gets t2 defined in the proper spot.

Categories

Resources