window.addEventListener('unload', function(e)
{
MyClass.shutdown();
window.removeEventListener('unload', /* how to refer to this function? */);
}, false);
The syntax is simple: you can simply declare the anonymous function and make it execute by just calling it using the parenthesis at the end of the function. You can simply pass the parameters inside the immediate execution of the anonymous function as we have seen in the above example.
To turn a normal anonymous function into a self-executing function, you simply wrap the anonymous function in parentheses and add a set of parentheses and a semicolon after it. The benefit of using self-executing anonymous functions is that the variables you create inside of them are destroyed when the function exits.
In JavaScript, an anonymous function is that type of function that has no name or we can say which is without any name. When we create an anonymous function, it is declared without any identifier. It is the difference between a normal function and an anonymous function.
The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .
Name your function.
function f(e) {
MyClass.shutdown();
window.removeEventListener('unload', f);
}
window.addEventListener('unload', f, false);
Edit I think this will work too. Good point Kobi!
window.addEventListener('unload', function f(e)
{
MyClass.shutdown();
window.removeEventListener('unload', f);
}, false);
Howto use recursion on Anonymous Functions
Lets say we have an anonymous factorial function and we want to do it recursively. How do we call a function without a name? Well in Javascript the arguments.callee property contains a pointer to the currently executing function which means an anonymous function can, indeed, call itself.
alert((function(n){ if(n <= 1){return 1;}else{return n*arguments.callee(n-1);}})(10));
source: http://www.hunlock.com/blogs/Functional_Javascript
The callee
property of the arguments
object always refers to the called function:
window.addEventListener('unload', function(e)
{
MyClass.shutdown();
window.removeEventListener('unload', arguments.callee);
}, false);
See: MDC: callee
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With