Today I Learned - Rocky Kev

TIL solving the this keyword and it's execution context

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.