Hello I am learning JavaScript and I was trying to understand how the the 'this' keyword.
Say I have the following JavsScript Code:
var a = function(){
console.log('this value for function a:');
console.log(this);
}
var obj = {
name: 'Object1',
objFunc: function(){
console.log('this value for function objFunc in Object1:');
console.log(this);
var nestedFunc = function(){
console.log('this value for nested function nestedFunc in Object1:');
console.log(this);
}
nestedFunc();
}
}
a();
obj.objFunc();
This results in the following:
- this value for function a: 'Window' object (the global object)
- this value for function objFunc in Object1: The object 'Object1'
- this value for nested function nestedFunc in Object1: 'Window' object (the global object)
Results 1,2 make sense to me.
- on examining Window object, a() is a function created as a method on the window global object so here 'this' points to it.
- on examining Object1 object, objFunc() is a function created as a method on the Object1 object so here 'this' points to it.
However I don't understand why the third result of nested func in object 'Object1' points to Window.
In the console if I examine the Window object and check its attributes I see that it has a field for a() so I can see why the 'this' for a() would point to Window. Similarly when I examine the object 'Object1' and check its attributes there is a field for objFunc() so I can see why the 'this' for objFunc() would point to Object1.
My questions are:
- I do not see a field for nestedFunc() in the Window object so why does 'this' in nestedFunc() point to the Window object?
- Although there is no separate attribute created in the Object1 object for nestedFunc(), the nestedFunc() function was created within Object1 so why does 'this' not point to Object1 instead of window?
Edit: I think my question has been answered by this website. From what I understand, closures cannot access the outer function’s 'this' variable by using the this keyword because the 'this' variable is accessible only by the function itself, not by inner functions. So 'this' for the nested function will be undefined hence it will be set to the global object