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?)
Why is JavaScript bind() necessary? The value of this is determined by how a function is called. If it is you who calls the function then there is usually no need to use . bind , since you have control over how to call the function, and therefore its this value.
A binding in JavaScript is the formal terminology for what a lot of people refer to as a variable. In ES2015+, a variable can be defined with the let keyword, but you can also define constant with the const keyword. A binding could refer to either a variable or a constant.
Default binding refers to how this is the global context whenever a function is invoked without any of these other rules. If we aren't using a dot and we aren't using call(), apply(), or bind(), our this will be our global object. Your global context depends on where you're working.
Rule #3: The JavaScript new Binding A new keyword is used to create an object from the constructor function. let Cartoon = function(name, character) { this.name = name; this. character = character; this. log = function() { console.
This 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-compatible 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 comma 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.
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