Hi I have following JavaScript code that I am trying to run. My aim is to grasp the meaning of this
in different scopes and different types of invocations in JavaScript.
If you look in code below: I have a inner anonymous function, which is getting assigned to innerStuff
variable. In that anonymous function as such this
points to window
object and not the outer function object or anything else. Event though it still has access to out function's variables.
Anyway, I am not sure, why that would be; but if you look at code below, I pass this
in form of that
to innerStuff
later and it works just fine and prints object with doofus
attribute in console.
var someStuff = {
doofus:"whatever",
newF: function()
{
var that = this;
console.log(that);
var innerStuff = function(topThis){
console.log(topThis);
};
return innerStuff(that);
}
}
someStuff.newF();
Now I am changing a code only little bit. And instead of assigning it to innerStuff
, I'll just directly return the function by invoking it as shown below:
var someStuff = {
doofus:"whatever",
newF: function()
{
var that = this;
console.log(that);
return function(that){
console.log(that);
}();
}
}
someStuff.newF();
This prints undefined for the inner anonymous function. Is it because there is a clash between a that
that is being passed as parameter and a that
defined in outside function?
I thought the parameter would have overriden the visibility. Why would the value be not retained?
This is utterly confusing.
On the other hand if I don't pass that
, but instead just use it, because visibility is there, the outcome is proper and as expected.
What is it that I am missing? Is it the clash between the variables, present in same scope?
Is there a good reason, that inner functions have this
bound to window
object?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…