6

When a function is attached to an object and called:

function f() { return this.x; }
var o = {x: 20};
o.func = f;
o.func(); //evaluates to 20

this refers to the object that the function was called as a method of. It's equivalent to doing f.call(o).

When the function is called not as part of an object, this refers to the global object. How do I check if a function is being called from a non-object context? Is there any standard keyword to access the global object? Is the only way to do it something like this?

globalobj = this;
function f() { if (this == globalobj) doSomething(); }

Note: I have no particular use case in mind here - I actually am asking about this exact mechanism.

3 Answers 3

9

The below should work since using Function.call with a value of null will invoke it in the global scope.

this === ((function () { return this; }).call(null))

A simpler variant,

this === (function () { return this; })()

will also work, but I think the first makes the intent clearer.

Sign up to request clarification or add additional context in comments.

1 Comment

The tags do not specify if this is browser only question and this answer works in both node.js and a browser
8

The global object is actually the window so you can do

if (this === window)

6 Comments

True at least if the script is running in a browser (since javascript now can be run in other places it might not be a universal truth)
is this a standard across browsers?
That depends on the browsers implementation of JavaScript engine, but that is mostly the case.
It's true for FF, IE, Opera and Chrome on Windows. A little more info: quirksmode.org/js/this.html
"Objects and this", "In a simple function call, this is set to the Global Object (aka window), which is not very useful.", javascript.crockford.com/survey.html
|
1

RoBorg's answer is conceptually correct -- except window is only available in the context of the browsers main thread (so this necessarily excludes worker threads and the like, as well as any non-browser hosted JS, which is getting less and less uncommon).

Your safest bet is basically what you had above, but you should use var and === as it is possible for the interpreter to optimise such accesses more completely.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.