I had a similar inquiry and eventually uncovered the solution, which goes as follows:
The situation is this
(0, foo.fn)();
It's important to note in JavaScript, when foo.fn()
is executed, the context of this
within fn
is linked to foo
. If you attempt
var g = foo.fn;
g();
when g
is called above, the reference for this
will be tied to the global object (window
, in a web browser setting).
Do we need to define g
in that manner? Could we do something like
(foo.fn)();
The answer is negative. JavaScript interprets it similarly to foo.fn();
since it is just foo.fn
with the redundant ()
that can be omitted.
However, there is a workaround, involving the use of the comma operator, as described by Mozilla
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand
So by using
(0, foo.fn)();
the expression (0, foo.fn)
gets assessed as a reference to the function, akin to g
previously, before being executed. Consequently, this
isn't connected to foo
but rather to the global object.
This approach essentially "cuts the binding".
For instance:
var foo = {
fullName: "Peter",
sayName: function() { console.log("My name is", this.fullName); }
};
window.fullName = "Shiny";
foo.sayName(); // My name is Peter
(foo.sayName)(); // My name is Peter
(0, foo.sayName)(); // My name is Shiny
Why would one want to cut the binding in certain scenarios? I came across a case where if we have a function:
function foo() {
// utilizing `this` here
}
Then this
would refer to the global object. However, if foo()
along with other functions and values are enclosed within a module, upon calling the function using
someModule.foo();
The this
would be bound to someModule
, altering the behavior of foo()
. To maintain the original behavior of foo()
, we sever the binding so that within foo()
, this
remains connected to the global object as before.