A Beginner’s Guide to Understanding the  difficulty behind the use of "this"

A Beginner’s Guide to Understanding the difficulty behind the use of "this"

Table of contents

Prerequisite

  • Knowledge of JavaScript (Object and function )

  • Know to use a Browser’s Dev Tools(Console.log).

  • A code editor and browser.

Introduction

The "this" keyword in JavaScript refers to a special variable that was created to carry out the concept of every function. It either takes or refers to the owner of the function value where the "this" keyword is used. Because the "this" keyword is not a static variable, it depends on how the function is called as well as how the value is assigned to the function.

When a method is called using the "this" keyword in a function method, the "this" keyword always points to the object that is calling the method as well as the object that is calling the method. Take a look at the image below, for example:

code.kennis.png

the method here is the calAge method and it's a function of the object Kennis, which the "this" keyword is called inside the method. the value of the "this" keyword will be the object Kennis because it's the object that is calling the method, which will have assess to the properties inside the object Kennis.

the value will be, check the

image below kennis

.age will be the same outcome with the "this" keyword.

code.kennis 3.png

Also, if the function is called has a normal function

code.kennis 4.png

the "this" keyword will simply result in an undefined

code.kennis 5.png

it is only valid when using the strict mode, if not using the strict mode,

code.kennis 6.png

the result to a global object also called a window object in the browser, which will cause problems in our code, and use strictly to prevent avoid that.

And in the Arrow function, the "this" keyword doesn't get its variables, while the Arrow function does not get its own "this" keyword, which makes it use the parent function, which is called a lexical scope, and the value result to a window object

code.kennis 7.png

The only solution to the "this" keyword complication is using the new, bind, call and apply was introduced.