开发者

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

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?


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


Not possible. The parentheses are how javascript knows that you want the method object to be executed.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜