Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  146] [ 1]  / answers: 1 / hits: 46584  / 13 Years ago, wed, september 21, 2011, 12:00:00

Is there a way in Javascript to define a function and immediately call it, in a way that allows it to be reused?



I know you can do one-off anonymous functions:



(function(i) {
var product = i * i;
console.log(product);
// Can't recurse here because there's no (ECMA standard) way for the
// function to refer to itself
}(2)); // logs 4


Or you can name a function then call it afterwards:



function powers(i) {
var product = i * i;
console.log(i * i);
if (product < 1e6) { powers(product) };
}

powers(2); // Logs 4, 16, 256...


But is there a cleaner way of defining and calling a function in one go? Sort of like a hybrid of both examples?



Not being able to do this isn't preventing me from doing anything, but it feels like it would be a nice expressive way to write recursive functions or functions that need to be run on $(document).ready() but also later when situations change, etc.


More From » recursion

 Answers
25

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.


[#89996] Monday, September 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;