What is ‘this’ referencing to in JavaScript?

The JavaScript this keyword refers to all the objects that exist in the function’s call-site.   A call-site of a function is the location where the function is called.

When a function’s call-site is inside an object, this refers to the object where the function belongs to. When a function’s call-site is in the window’s object, this refers to the global objects.

If you are not familiar with this, the explanation above is probably not sufficient. Let’s have a look at actual examples.

Example

Can you tell the output of this code example?

Output

Here is the output from the code example above.

hello
global
hello
hello

Explanation

The function b’s call-site is the check object. Therefore, this.a refers to a that blongs to the check object.

In the function c, setTimeout’s call-site is the windows object (window.setTimeout). Therefore, this refers to the global object. Hence, this.a is from the global scope. If you delete a in the global namespace, this.a becomes undefined.

The function d uses the old school technique of reassigning this to _this. By using _this, setTimeout has access to the a variable within the check object.

ES6 arrow function introduced lexical scope. Therefore, this refers to the check object in the function e as we are using the arrow function for the setTimeout callback function.

Hope this helps you to clarify this.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …