I am trying to understand JavaScript this better.
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
this
context in JavaScript depends on how the function is being called. See What does "this" mean?.
this
will refer to window
function foo() {
console.log(this);
}
foo();
Here, foo
is globally defined function and the call to foo()
is like window.foo()
, Thus this
inside foo()
refers to the window
object.
Uncaught SyntaxError: Unexpected token this(…) on chrome console.
function foo(this) {
console.log(this);
}
foo();
this
is reserved keyword and cannot be used as identifier name. Also note that no parameter is passed to foo()
when invoking the function.
undefined
is logged in below code
var that = this; // Global that
function foo(that) { // Parameter `that`
console.log(that); // <-- Use semicolon here
}
foo(); // `that` is not passed.
because that
passed as parameter overshadows the global that
. And as nothing is passed to foo()
, undefined
is logged.