TIL solving the this keyword and it's execution context
POSTED ON:
TAGS: javascript advanced
The this
keyword in Javascript is, to put it lightly, oddly difficult the more you think about it.
The easiest way to describe it is:
The this
keyword references the current execution context of the function from where you’re calling using it.
That means:
If you’re using it inside a regular function:
It’ll be the execution context of that function.
If you’re using it inside an arrow function:
Then it’ll reference the execution context of the parent function.
That is, if you’re calling this arrow function within a regular function, the latter will act as a parent function.
If you’re using the arrow function at the top level, then you’re accessing the global scope.
If you’re using it inside a method:
You’re referencing the execution context of that method, which also includes all the properties defined as part of the class of that object.
class Person {
constructor(first_name, last_name) {
this.fName = first_name;
this.lName = last_name;
}
}
function greetPerson() {
console.log("Hello there ", this.fName, this.lName);
}
let newPerson1 = new Person("Fernando", "Doglio");
let newPerson2 = new Person("John", "Doe");
greetPerson.call(newPerson1);
greetPerson.call(newPerson2);
Via:
Javascript Worst Practice
Related TILs
Tagged: javascript