什么是“这个"?在一个函数的调用语句中引用,作为另一个函数的方法 [英] What does "this" refer to in a call statement in a function, as a method of another function
问题描述
如果我看到带有这样的构造函数的代码:
If I see a code with constructor functions like this:
function F(){}
F.prototype.k = "v";
function F2(){
F.call(this);
}
这里的这个"指的是什么?我有点迷路了.是F2还是F?
What does "this" refer to here? I'm kind of lost. Would it be F2 or F?
推荐答案
此
在任何函数中均由该函数的调用方式决定,而您未显示 F2()()将调用code>,但是此代码的作用是说,在
F2
中将 this
设置为什么,当 this
使用相同的值 F()
被执行.
this
in any function is determined by how the function is called and you do not show how F2()
is called, but what this code is doing is saying that whatever this
is set to in F2
, use the same value for this
when F()
is executed.
-
如果像这样
F2()
一样调用F2()
,则this
将是全局对象(<代码>窗口(在浏览器中)或undefined
(如果在严格模式下运行).
If
F2()
is called just like thisF2()
, thenthis
will be either the global object (window
in a browser) orundefined
(if running in strict mode).
如果按以下方式调用 F2
:
var obj = new F2();
然后,将 this
设置为新创建的 F2
实例.
Then, this
would be set to the a newly created instance of F2
.
方法 F2.apply(x)
和 F2.call(x)
可以确定将此为此
设置为在给定的函数中根据您作为第一个参数传递的内容.
The methods F2.apply(x)
and F2.call(x)
can determine what this
will be set to in a given function based on what you pass as the first argument.
如果它是 obj.method()
中的方法调用,则 this
设置为 obj
.p>
If it's a method call as in obj.method()
, then this
is set to the obj
.
这篇关于什么是“这个"?在一个函数的调用语句中引用,作为另一个函数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!