简体   繁体   中英

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!)

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.

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.

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

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.

[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
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM