Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - check if in global context

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.

like image 274
Claudiu Avatar asked Dec 20 '08 10:12

Claudiu


2 Answers

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.

like image 54
Mike Samuel Avatar answered Oct 27 '22 02:10

Mike Samuel


The global object is actually the window so you can do

if (this === window)
like image 22
Greg Avatar answered Oct 27 '22 02:10

Greg