JavaScript - 检查是否在全局上下文中
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)
.
这指的是函数被称为方法的对象。这相当于做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 个解决方案
#1
The global object is actually the window so you can do
全局对象实际上是窗口,因此您可以这样做
if (this === window)
更多相关文章
- 高效地获取XMLhttp对象
- javascript面向对象技术基础
- Javascript学习:案例7--对象属性和方法的遍历、删除、添加.html
- JavaScript String对象方法——replace()
- ABP(现代ASP.NET样板开发框架)系列之21、ABP展现层——Javascrip
- 为什么括号用于包装javascript函数调用? [重复]
- Javascript正则表达式对象和美元符号
- javascript 构造函数中的属性与原型上属性优先级的比较
- 将JavaScript对象转换为要插入关系数据库的数组