I read about the ES6 arrow function's scope in the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#call_apply_and_bind
While I feel like it does sufficiently explain how an arrow function works. when I read these 2 example code below, I still don't quite understand why the traditional way of calling functions are able to get window as this.
Traditional Example (taken from MDN web docs):
var obj = {
count : 10,
doSomethingLater : function (){
setTimeout(function(){ // the function executes on the window scope
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater(); // console prints "NaN", because the property "count" is not in the window scope.
Arrow Example (taken from MDN web docs):
var obj = {
count : 10,
doSomethingLater : function(){ // of course, arrow functions are not suited for methods
setTimeout( () => { // since the arrow function was created within the "obj", it assumes the object's "this"
this.count++;
console.log(this.count);
}, 300);
}
}
obj.doSomethingLater();
After seeing the above 2 examples, I played around a bit and wrote this, let's call this example 3:
var obj = {
count : 10,
doSomethingLater : function (){
// this.count is not undefined here
function namedFn(){
console.log(this.count);
console.log(this); //why is this window?
}
namedFn();
}
}
obj.doSomethingLater();
Now, I also read that let's say we have function A, and function B is declared within function A, function B's scope is enclosed in function A. something like this:
// global scope
function foo(a) {
//foo scope
var b = a * 2;
function bar(c) {
// bar scope
console.log( a, b, c );
}
bar(b * 3);
}
foo( 2 ); // 2 4 12
So inside bar, I understand we still know what a
is even though a
is not defined in that scope. What am I missing in concepts that makes Example 3's inner console.log to be undefined and this to be window? How is it able to grab a global scope when it is within another function?
As for the 2 questions that this is marked as a duplicate of: 1 was asking why arrow function's this is referring to its parent scope. Which I think it's clear that I'm not asking that. 2 was a very generic question of "what this key work does"? Maybe this question can be a sub-section of that? but to say a generic question asking what "this" does is a dupe is a little stretch.