Martin Burch
Martin Burch

Reputation: 2911

Any reason to have a function as a variable?

Editing someone else's code, I ran across a pattern I had not previously seen:

var functionName = function functionName(){};

and sometime later, to call the function, using this jQuery

$(functionName);

Now, before I change it to the standard function functionName(){} called with functionName();, is there any reason to do it the other way?

EDIT: Updated to reflect the use of jQuery in the function call. I oversimplified the example. (Oops! Sorry!)

Upvotes: 1

Views: 85

Answers (5)

JoDev
JoDev

Reputation: 6873

[EDIT]
You can find var functionName = function(){}; and make as many instance this way var second = functionName;
It's helpful only if you want to have few variables to call the same function, but with a different param...

But in your case, functionName will contain only that the function functionName() {}; will return.

You propably have something like this in the function content:

var functionName = function test(param) {
    [...]
    return function(otherParam) { 
        //do something
    };
}

Upvotes: -1

djna
djna

Reputation: 55907

var workerFn = function someDefaultFn() {};

if ( lots of logic) {
  workerFn = function specialFn() {};
}

//// later on

workerFn();

So now we have flexibility as to what exactly is invoked. Sort of a poor-man's polymorphism.In your example we'd be passing the workerfn to JQuery to be invoked, so same possibility for flexibility.

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816384

The only technical reasons for using a function expression would be to avoid hoisting of the function and/or being able to use another internal name to refer to the function itself.

These are the only differences between function expressions and function declarations and it depends on the context whether they are relevant at all.

Upvotes: 1

Nivas
Nivas

Reputation: 18334

functionName;

would not call the function. This is just a reference to the function. Calling the function needs the (). So if we have

var functionName = function test(){ alert("0");};

this

functionName;

does not call it. Actually this does not do anything at all (no-op). This is same as

var x;
x;

Only this

functionName()

calls it.

Maybe the functionName; is used for something else. We can tell only if we have context.

Upvotes: 0

laktak
laktak

Reputation: 60003

I'd say it's a bug because functionName; will not do anything. Or is it a typo in your question?

Upvotes: 0

Related Questions