Invoking a function without parentheses

Invoking a function without parentheses

I was told today that it’s possible to invoke a function without parentheses. The only ways I could think of was using functions like apply or call.
f.apply(this);
f.call(this);

But these require parentheses on apply and call leaving us at square one. I also considered the idea of passing the function to some sort of event handler such as setTimeout:
setTimeout(f, 500);

But then the question becomes “how do you invoke setTimeout without parentheses?”
So what’s the solution to this riddle? How can you invoke a function in Javascript without using parentheses?

Solutions/Answers:

Solution 1:

There are several different ways to call a function without parentheses.

Let’s assume you have this function defined:

function greet() {
    console.log('hello');
}

Then here follow some ways to call greet without parentheses:

1. As Constructor

With new you can invoke a function without parentheses:

new greet; // parentheses are optional in this construct.

From MDN on the new oprator:

Syntax

new constructor[([arguments])]

2. As toString or valueOf Implementation

toString and valueOf are special methods: they get called implicitly when a conversion is necessary:

var obj = {
    toString: function() {
         return 'hello';
    }
}

'' + obj; // concatenation forces cast to string and call to toString.

You could (ab)use this pattern to call greet without parentheses:

'' + { toString: greet };

Or with valueOf:

+{ valueOf: greet };

2.b Overriding valueOf in Function Prototype

You could take the previous idea to override the valueOf method on the Function prototype:

Function.prototype.valueOf = function() {
    this.call(this);
    // Optional improvement: avoid `NaN` issues when used in expressions.
    return 0; 
};

Once you have done that, you can write:

+greet;

And although there are parentheses involved down the line, the actual triggering invocation has no parentheses. See more about this in the blog “Calling methods in JavaScript, without really calling them”

Related:  Adding options to a

Recent Posts

Categories

Recent Comments