问题
My guess is that this is not possible, but I'd like f and f() to do the same thing.
var f = function(str){ console.log(str||'foo'); }();
f; // wanted output: 'foo'
f(); // wanted output: 'foo'
f('bar'); // wanted output: 'bar'
Because f is no longer a function definition, it doesn't seem possible to do f(), but maybe I'm missing something. Any suggestions?
回答1:
No that is not possible. The parentheses are required to determine that the function should be called.
The value of the expression f() is the result of calling the function, while the value of f is the function itself (and f.tostring() if you display it).
回答2:
Not possible. The parentheses are how javascript knows that you want the method object to be executed.
回答3:
Remove the () from your def.
var f = function(str){ console.log(str||'foo'); };
Except your first case, all of them will work. You need to specify () to tell javascript to execute the function
来源:https://stackoverflow.com/questions/3761069/how-to-implement-optional-parentheses-during-function-call-function-overloadin