I've noticed that babel transpiled
import { install } from 'source-map-support';
install();
into
var _sourceMapSupport = require('source-map-support');
(0, _sourceMapSupport.install)();
Why did babel use the comma operator with 0
as first expression in the invocation of the install
function?
The comma is explained in What does a comma do in JavaScript expressions?. basically, it evaluates all the expressions, and returns the value returned by the last one.
Probably, the reason for using that is to be able to call the method as if it weren't a method.
Consider this function:
function f() { return this; }
And let's make it a method:
var o = {f: f}
Then, although f === o.f
, the result will vary depending on how you call it:
o.f(); // o
f(); // global object (in non-strict mode)
f(); // undefined (in strict mode)
So babel uses the comma approach to get a reference to the function, without associating it with the object. This way the method can be called as if it were a global function, without being one.
(0, o.f)(); // global object (in non-strict mode)
(0, o.f)(); // undefined (in strict mode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With