Invoking functions without parens!

node v8.16.2
version: master
endpointsharetweet
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:
foo.bar
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:
foo["bar"]
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:
bar
Another fun way might be assigning the property to `global`!
Object.defineProperty(global, "lol", descriptor); global.lol
Because everything on the global object is ... well... global, we can invoke the function just like this:
lol
Tagged functions using tempate literals:
descriptor.get`tagged`
As a constructor!
new descriptor.get
Loading…

no comments

    sign in to comment