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)

更多相关文章

  1. 高效地获取XMLhttp对象
  2. javascript面向对象技术基础
  3. Javascript学习:案例7--对象属性和方法的遍历、删除、添加.html
  4. JavaScript String对象方法——replace()
  5. ABP(现代ASP.NET样板开发框架)系列之21、ABP展现层——Javascrip
  6. 为什么括号用于包装javascript函数调用? [重复]
  7. Javascript正则表达式对象和美元符号
  8. javascript 构造函数中的属性与原型上属性优先级的比较
  9. 将JavaScript对象转换为要插入关系数据库的数组

随机推荐

  1. Linux系统的文件传输工具RZSZ
  2. 使用wdcp完成网站搭建
  3. linux忘记root密码的两种修改方法
  4. Linux Socket编程(不限Linux)
  5. Git - 将Github仓库与本地仓库同步?
  6. 新人求助:tensorflow官方文档里构建第一个
  7. Linux 驱动开发之内核模块开发 (三)—— 模
  8. 文本处理小工具SED用法
  9. Linux学习之文件系统权限及表示
  10. Linux daemon进程的应用、实现和原理