If I see a code with constructor functions like this:
function F(){}
F.prototype.k = "v";
function F2(){
F.call(this);
}
What does "this" refer to here? I'm kind of lost. Would it be F2 or F?
If I see a code with constructor functions like this:
function F(){}
F.prototype.k = "v";
function F2(){
F.call(this);
}
What does "this" refer to here? I'm kind of lost. Would it be F2 or F?
this
in any function is determined by how the function is called and you do not show howF2()
is called, but what this code is doing is saying that whateverthis
is set to inF2
, use the same value forthis
whenF()
is executed.If
F2()
is called just like thisF2()
, thenthis
will be either the global object (window
in a browser) orundefined
(if running in strict mode).If
F2
is called like:var obj = new F2();
Then,
this
would be set to the a newly created instance ofF2
.The methods
F2.apply(x)
andF2.call(x)
can determine whatthis
will be set to in a given function based on what you pass as the first argument.If it's a method call as in
obj.method()
, thenthis
is set to theobj
.