最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

object - JavaScript - check if in global context - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited May 11, 2014 at 18:52 nicael 19k13 gold badges61 silver badges91 bronze badges asked Dec 20, 2008 at 10:42 ClaudiuClaudiu 229k173 gold badges503 silver badges698 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

The global object is actually the window so you can do

if (this === window)

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 unmon).

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 pletely.

发布评论

评论列表(0)

  1. 暂无评论