The reason of using a
(0, foo.fn)();
is to cut the binding: the this
will not longer be bound to foo
but will be bound to the global object.
But what is the reason why any JavaScript code (or Google's JS code) would want to cut the binding? (and is it an anti-pattern or not?)
The reason of using a
(0, foo.fn)();
is to cut the binding: the this
will not longer be bound to foo
but will be bound to the global object.
But what is the reason why any JavaScript code (or Google's JS code) would want to cut the binding? (and is it an anti-pattern or not?)
Share Improve this question edited Dec 1, 2019 at 11:15 nonopolarity asked Dec 1, 2019 at 11:09 nonopolaritynonopolarity 151k142 gold badges492 silver badges782 bronze badges 4-
calling it a binding doesn't feel right.
bind
method binds. Here it's just a context change. You can't cut or lose binding (the bond created bybind
). – marzelin Commented Dec 1, 2019 at 11:26 - maybe this code is generated by a transpiler from some functional language (clojurescript?) that has specific requirements when it es to calling functions? – marzelin Commented Dec 1, 2019 at 11:37
- 1 possible duplicate of Why does babel rewrite imported function call to (0, fn)(…)? - or where else are you seeing this? – Bergi Commented Dec 1, 2019 at 13:12
- I think I saw it in Google's code and possibly in some framework like Angular, React, or some other ones... can't recall where and sometimes it is minified – nonopolarity Commented Dec 1, 2019 at 14:43
1 Answer
Reset to default 13This kind of code is typically generated by transpilers (like Babel), in order to convert modern JavaScript -- that uses the most recent additions to the specification -- to a JavaScript version that is more widely supported.
Here is an example where this transpilation pattern occurs:
Let's say we have this original code before transpilation:
import {myfunc} from "mymodule";
myfunc();
To make this ES5-patible code, you could do this:
"use strict";
var mymodule = require("mymodule");
mymodule.myfunc();
But here we would execute myfunc
with mymodule
as this
value, which is not happening in the original code. And although that might not always be an issue, it is better to make sure the function behaves just like it would in the original version, even if that function would use a this
reference -- how unusual or even useless that use of this
in myfunc
might be (because also in the original version it would be undefined
).
So for instance, if the original code would throw an error because of a this.memberFun()
reference in the function, it will also throw in the transpiled version.
So that is were the ma operator is used to get rid of that difference:
(0, mymodule.myfunc)();
Granted, in code that you write yourself, you would never have a good use case for this pattern, as you would not use this
in myfunc
in the first place.