Defining and calling function in one step
You can try:
(window.powers = function(i) {
/*Code here*/
alert('test : ' + i);
})(2);
<a href="#" onclick="powers(654)">Click</a>
Working link : http://jsfiddle.net/SqBp8/
It gets called on load, and I have added it to an anchor tag
to change the parameter and alert
.
If all you want is access the function within its own body, you can simply specify a name after the function
keyword:
> (function fac (n) {
return (n === 0 ? 1 : n*fac(n-1));
})(10)
3628800
This is a standard feature (see ECMA-262, ed. 5.1, p. 98).
All the answers here are close to what you want, but have a few problems (adding it to the global scope, not actually calling it, etc). This combines a few examples on this page (although it unfortunately requires you to remember arguments.callee
):
var test = (function() {
alert('hi');
return arguments.callee;
})();
Later, you can call it:
test();
If you don't care about the return value, you can do this.
var powers = function powers(i) {
var product = i * i;
console.log(i * i);
if (product < 1e6) { powers(product) };
return powers;
}(2);