A JavaScript Quirk
It’s common knowledge that JavaScript has its fair share of quirks. But this is one I find particularly interesting. (0, fn)()
acts as a way to unbind this
and execute a function without a context. This is because fn
is now being treated as an lvalue.
class Test {
constructor() {
this.member = "I EXIST";
}
logThis() {
console.log("Logging:", this);
}
}
const instance = new Test();
instance.logThis();
// Logging: Test {member: 'I EXIST'}
(0, instance.logThis)();
// Logging: undefined
In the example above, it’s equivalent to calling the logThis
method using instance.logThis.bind(undefined)()
.