Billy Moon
Billy Moon

Reputation: 58601

Is it possible to execute anonymous function twice?

I want to define a self executing anonymous function, but have it run several times with different parameters.

(function(x){ console.log(x*x)})(2)
// output: 4

// I know this syntax is wrong, I am
// demonstrating how I would imagine it being implemented
(function(x){ console.log(x*x)})(2)(5)
// output is error, desired output: 4{Newline}25

Is it possible?


Edit: Based on answer from @Charmander, it seems it is possible and almost certainly a bad idea, but this works as I would expect...

(function(x){ console.log(x*x); return arguments.callee})(2)(5)

Upvotes: 3

Views: 1623

Answers (2)

Dan Tao
Dan Tao

Reputation: 128377

I'd say you can do it just fine:

var f = function(x) {
    console.log(x**x);
    return f;
};

f(5)(6)(7);

See here for a working example:

http://jsfiddle.net/9qAgr/

Now, I will grant you, the above is not really an anonymous function in the sense that I have sort of given it a name (f); so if you literally meant: "Is it possible to do this without having any way of referring back to the function itself?" then I doubt it. Though I could just be lacking in imagination ;)


You can actually have even more fun with this (if you're a nerd like me, which you probably are since you're on this site) by defining a function that returns itself while maintaining state at the same time, thanks to JavaScript's ability to add properties to functions:

function createCalculator(operation) {
    var result = 0;

    var calculator = function(x) {
        result = operation(x, result);
        return calculator;
    };

    calculator.result = function() {
        return result;
    };

    return calculator;
};

var add = createCalculator(function(x, y) { return x + y; });

console.log(add(1)(2)(3)(4).result());

And here's a demo if you want to see for yourself:

http://jsfiddle.net/9qAgr/1/

Upvotes: 1

dqhendricks
dqhendricks

Reputation: 19251

You can either store the anonymous function in a variable.

var someFunction = function(x){
   console.log(x*x);
};

someFunction(5);
someFunction(6);

Or you could have the function return itself if you are really bent on making it an immediately-invoked function expression (iife).

(function(x){
   console.log(x*x);
   return arguments.callee;
})(5)(6);

Upvotes: 6

Related Questions