Invoking functions without parens!

node v8.17.0
version: master
Normally in Javascript functions are invoked using parentheses. But there are a few ways to invoke functions without them. Often times this is by accident, but it's worth knowing them! The most common way will be because a property is implemented as a getter or setter. See the setup:
const foo = {}; const descriptor = { get: function(){ console.log("getter invoked"); return "blah"; }, set: function(aValue){ console.log("setter invoked"); return 123; } }; Object.defineProperty(foo, "bar", descriptor);
These kinds functions are most likely to be invoked this way:
If you didn't know this property was implemented as a getter, or you did and you just wanted to get a reference to the function, you may naively try to get access like this:
Whoops! Another common practice might be to try to use destructuring:
const { bar } = foo; bar
This will invoke the getter once, but the value will be stored so it won't be invoked again:
Another fun way might be assigning the property to `global`!
Object.defineProperty(global, "lol", descriptor);
Because everything on the global object is ... well... global, we can invoke the function just like this:
Tagged functions using tempate literals:
As a constructor!
new descriptor.get

no comments

    sign in to comment