How to implement optional parentheses during function call? (function overloading)

折月煮酒 提交于 2019-12-13 05:06:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!