Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining and calling function in one step

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.

like image 658
quis Avatar asked Sep 21 '11 10:09

quis


People also ask

How do you define and call a function?

When you define a function you give a name to a set of actions you want the computer to perform. When you call a function you are telling the computer to run (or execute) that set of actions.

Is calling and defining a function the same thing?

Answer 52ef011652f8638f83001243. declare and define are the same, and they mean when you write all the code for your function. At that point the function just sits there doing nothing. call is when you tell the JavaScript interpreter to run the code in your function.

How do you define and call a function in JavaScript?

Use the keyword function followed by the name of the function. After the function name, open and close parentheses. After parenthesis, open and close curly braces. Within curly braces, write your lines of code.


1 Answers

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.

like image 150
Marc Uberstein Avatar answered Oct 05 '22 09:10

Marc Uberstein