I want to safely parse the value of this, in a global function, while accounting for whether this was explicitly set via call, apply or bind on the function.
In NodeJS, the following seems to work correctly:
function checkThis() {
const defaultThis = require.main.children[0].exports;
console.log(this === defaultThis);
}
checkThis(); //=> true
checkThis.call(); //=> false
checkThis.apply(); //=> false
Is there any JavaScript-generic alternative to this that would work both in browsers and NodeJS?
Perhaps you can use globalThis in browser land.
The global globalThis property contains the global this value, which is akin to the global object.
Note the comment by @Simon, your code in your example will not work in non-strict mode
When working with this, make sure to always use strict mode to get the value that was actually passed, not something coerced to an object or defaulted to the global object.
However, it is not really possible to detect whether a this argument was explicitly set with call/apply/bind or whether the function was called directly, every call does pass a this argument even if it's undefined:
function checkThis() {
"use strict";
console.log(this);
}
checkThis(); // undefined
checkThis.call(); // undefined
checkThis.apply(); // undefined
checkThis.bind()(); // undefined
If you really needed to detect call/apply/bind, you'd need to overwrite these methods on your concrete function.
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