JavaScript:什么是全局对象,“this”在哪里?参考? [英] JavaScript: What's global object and where does "this" refer to?
问题描述
我已经了解到在函数调用中,这个
会引用全局对象。在下面的函数中,哪个是全局对象?
I've learned that in function invocation, this
would refer to the global object. In the function below, which is the global object?
是函数还是有一个默认的全局对象,其中这个
会参考?除此之外,这段代码实际上做了什么?我对方法
占位符特别感到困惑。它是否必须替换为Function.prototype中预先存在的方法?
Is it the Function or there's a single default global object where this
would refer to? In addition to that, what does this code actually do? I am particularly confused about the method
placeholder. Does it have to be replaced with a method that's pre-existing in Function.prototype?
并且在行 this.prototype [name] = func;
,它指的是哪个属性,方法或函数.prototype?
And in the line this.prototype[name] = func;
, which property is it referring to, the method's or the Function.prototype's?
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
推荐答案
this
keyword是指当前对象,如果函数的作用域是全局名称空间,则当前对象是全局对象,即窗口
对象,如果环境是一个浏览器。
The this
keyword refers to the current object, and if the scope of a function is the global namespace, the current object is the global object, i.e. the window
object if the environment is a browser.
当您向 Function
类添加方法时,此
关键字将引用您正在调用方法
方法的函数,因此它将返回函数本身,以便调用可以链接。
As you are adding a method to the Function
class, the this
keyword will refer to the function that you are calling the method
method on, so it will return the function itself so that the calls can be chained.
这将声明函数 F
作为构造函数,创建一个<$ c $类型的对象c> F ,将函数 x
添加为 F
的方法并命名为 xx
,然后使用对象 f
来调用 xx
是 x
:
This will declare the function F
as a constructor, create an object of the type F
, add the function x
as a method to F
and name it xx
, then use the object f
to call xx
which really is x
:
function F() {}
function x() { alert(1); }
var f = new (F);
F.method('xx', x);
f.xx();
所以,这个:
F.method('xx', x).method('yy', y);
与以下内容相同:
F.prototype.xx = x;
F.prototype.yy = y;
这篇关于JavaScript:什么是全局对象,“this”在哪里?参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!