Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  27] [ 7]  / answers: 1 / hits: 101491  / 8 Years ago, fri, march 11, 2016, 12:00:00

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?


More From » javascript

 Answers
32

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

valueOf and toString are in fact called from the @@toPrimitive method (since ES6), and so you can also implement that method:


+{ [Symbol.toPrimitive]: greet }
"" + { [Symbol.toPrimitive]: 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"


3. As Generator


You could define a generator function (with *), which returns an iterator. You can call it using the spread syntax or with the for...of syntax.


First we need a generator variant of the original greet function:


function* greet_gen() {
console.log('hello');
}

And then we call it without parentheses by defining the @@iterator method:


[...{ [Symbol.iterator]: greet_gen }];

Normally generators would have a yield keyword somewhere, but it is not needed for the function to get called.


The last statement invokes the function, but that could also be done with destructuring:


[,] = { [Symbol.iterator]: greet_gen };

or a for ... of construct, but it has parentheses of its own:


for ({} of { [Symbol.iterator]: greet_gen });

Note that you can do the above with the original greet function as well, but it will trigger an exception in the process, after greet has been executed (tested on FF and Chrome). You could manage the exception with a try...catch block.


4. As Getter


@jehna1 has a full answer on this, so give him credit. Here is a way to call a function parentheses-less on the global scope, avoiding the deprecated __defineGetter__ method. It uses Object.defineProperty instead.


We need to create a variant of the original greet function for this:


Object.defineProperty(window, 'greet_get', { get: greet });

And then:


greet_get;

Replace window with whatever your global object is.


You could call the original greet function without leaving a trace on the global object like this:


Object.defineProperty({}, 'greet', { get: greet }).greet;

But one could argue we do have parentheses here (although they are not involved in the actual invocation).


5. As Tag Function


Since ES6 you can call a function passing it a template literal with this syntax:


greet``;

See "Tagged Template Literals".


6. As Proxy Handler


Since ES6, you can define a proxy:


var proxy = new Proxy({}, { get: greet } );

And then reading any property value will invoke greet:


proxy._; // even if property not defined, it still triggers greet

There are many variations of this. One more example:


var proxy = new Proxy({}, { has: greet } );

1 in proxy; // triggers greet

7. As instance checker


The instanceof operator executes the @@hasInstance method on the second operand, when defined:


1 instanceof { [Symbol.hasInstance]: greet } // triggers greet

[#62971] Wednesday, March 9, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidengiancarlop

Total Points: 234
Total Questions: 115
Total Answers: 94

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;