What is this?
this is a keyword in javascript and many other programming languages.
this has different meanings in different contexts but in general, it refers to the object that is executing the current code.
this has different meaning the below mentioned contexts.

1. When used inside a method of an object, this refers to that object.

2. When used inside a normal function that does not belong to an object or outside any function, this refers to the window object(also referred as global object).
1. this inside object method
An object in javascript is a group of properties in key-value pairs and functions. Example,

let laptop = {
               name: 'Latitude',
               brand: 'Dell',
               RAM: '16GB',
               HDD: '350GB',
               print: function() {
                        console.log(this);
                      }
              };

Above object has a function named print.
If this is used inside the function it will refer to that object only. Thus, above code when executed will output.

{name: Latitude, brand: Dell, RAM: 16GB, HDD: 350GB, print: ƒ}
HDD350GB
RAM16GB
brandDell
nameLatitude
printƒ ()
__proto__Object

As you can see, this output is the same object.

Objects in detail can be studied here.

When this is used inside a method of an object, it can access the properties of the object. Example,

 let laptop = {
               name: 'Latitude',
               brand: 'Dell',
               RAM: '16GB',
               HDD: '350GB',
               print: function() {
                        console.log('Name: '+this.name);  // prints 'Name: Latitude'
                      }
              };

2. this inside a normal function or alone
When used in a function that does not belong to any object or directly in javascript code that is not inside any function, this refers to the window object.
Example,

function outside() {
   console.log(this);
}
outside();

It produces the below output.

Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

When this is used outside of any function, then also it refers to the window object. Example,

let alone = this;
console.log(alone);

Above code produces the following output.

Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

 

Leave a Reply