I am trying to understand JavaScript this better.
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
this refers to the current context of execution in Javascript. This context is something that Javascript keeps to itself and it is readonly. You can only read the variables available in that context. You cannot override it. When you do something like this:
function foo(this){
console.log(this);
}
foo();
with the parameter this in the function, you are trying to overwrite the current context which is not allowed and hence you get the error.
And, when you run this code:
var that = this;
function foo(that){
console.log(that):
}
foo();
you are not passing any parameter while calling the foo function and hence the value of that is undefined. Note that the earlier assignment of this to that is overwritten in this foo function context.
Refer this link and this to know more about execution context.