Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if "this" was specified

Tags:

javascript

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?

like image 206
vitaly-t Avatar asked Mar 10 '26 07:03

vitaly-t


2 Answers

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

like image 152
thedude Avatar answered Mar 12 '26 20:03

thedude


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.

like image 20
Bergi Avatar answered Mar 12 '26 22:03

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!