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 Ja
In your second example, when you invoke the anonymous function, the parameter that
is not defined (you aren't passing anything to it.) You can do this:
newF: function()
{
var that = this;
console.log(that);
return function(that){
console.log(that);
}(that); // note that we are passing our 'that' in as 'that'
}
That will keep the proper value of the variable around.
However, since you are scoping var that
above, you could just remove the function parameter as well:
newF: function()
{
var that = this;
console.log(that);
return function(){
console.log(that);
}(); // 'that' is referenced above.
}
As far as why anonymous functions have window
as their this
: whenever you call a function without a context (i.e. somef()
vs context.somef()
) this
will point to the window
object.
You can override that and pass a this
using .apply(context, argumentsArray) or .call(context, arg1, arg2, arg3) on a function. An example:
newF: function()
{
console.log('Outer:', this);
var innerF = function(){
console.log('Inner:', this);
};
return innerF.apply(this,arguments);
}