Sunday, 26 July 2020

Understand the 'this' keyword in JavaScript

Objects are the basic building blocks in javascript.There's one special object available in javascript,the
'this' object.you can see the value of 'this' at every line of javascript execution.The value of 'this' is decided based on how the code is being executed.

Execution Context :

The environment (or scope) in which the line is being executed is known as the 'execution context'.
The javascript runtime maintain a stack of these execution contexts,and the execution context present 
at the top of this stack is the one currently being executed.The object 'this' refers to changes every time the execution context is changed.


Note : The value of 'this' differs depending on how a function is invoked,so we can't know the value of 'this' just by looking at the function itself,but we need to know the context in which the function is invoked.

'this' keyword refers to the object it belongs to

1.In a method,'this' refers to the owner object.
  ex :
   let person={
    firstName:"John",
lastName:"Doe",
getFullName : function(){
  return this.firstName+" "+this.lastName;
}   
   };
   
   person.getFullName(); // John Doe      
 
2.Alone,'this' refers to the global object.

Note : 'this' refers to a Global Object.

By default,the execution context for an execution is global - which means if a code is being executed as part of a simple function call,then 'this' refers to a global object.

The 'window' object is the global object in the case of the browser.And in a NodeJS environment, a special object called 'global' will be the value of 'this'.

ex :
function foo() {
  console.log(this); // window
}
foo(); 
console.log(this); // window


  
3.In a function,'this' refers to the global object.

 ex : Immediately Invoked Function Expression (IIFE)

  (function(){
console.log("Anonymous function invocation");
console.log(this === window);
})();

4.In a function,in strict mode,'this' is undefined.
  
  If strict mode is enabled for any function, then the value of 'this'   will be marked as 'undefined' as in strict mode.The global object refers   to 'undefined' in place of the 'window' object.
  
 ex :
   function foo () {
'use strict';
console.log("Simple function call")
console.log(this); // undefined
}

In strict mode the value of 'this' in a global-execution context is 'undefined'.

5.In an event,'this' refers to the element that received the event.

 ex : <button onclick="foo(this)"></button>
    function foo(e){
        console.log(e); // <button onclick="foo(this)"></button>
    }

6.Methods like call(),and apply() can refer this to any object.

Note : 'this' with the call and apply methods.

A function in Javascript is also a special type of object.Every function has 
'call','bind' and 'apply' methods.These methods can be used to set a custom value
to 'this' in the execution context of the function.

ex : let obj = {name:"Harish"};
     let greeting = function(a,b,c){
          console.log("welcome "+this.name+" to "+a+" "+b+" in "+c);
    };
  greeting.call(obj,"Newton","KOLKATA","WB"); 
   // welcome Harish to Newtown KOLKATA in WB
   
The first parameter in call() method sets the "this" value, which is the object, on which the function is invoked upon. In this case, it's the "obj" object above.

The rest of the parameters are the arguments to the actual function.

ex :  let obj = {name:"Harish"};
     let greeting = function(a,b,c){
          console.log("welcome "+this.name+" to "+a+" "+b+" in "+c);
    };
let args=["Newton","KOLKATA","WB"];
  greeting.apply(obj,args); 
   // welcome Harish to Newtown KOLKATA in WB 

The only difference between the 'call' and 'apply' methods is the way an 
argument is passed.In the case of 'apply',the second argument is an array 
of arguments,whereas in the case of the 'call' method,the arguments are passed 
individually.

The 'bind' method returns a new method with 'this' referring to the first argument passed.

ex : let obj = {name:"Harish"};
     let greeting = function(a,b,c){
          console.log("welcome "+this.name+" to "+a+" "+b+" in "+c);
    };
    let bound = greeting.bind(obj); 
bound("Newtown","KOLKATA","WB");   // welcome Harish to Newtown KOLKATA in WB

Note : 'bind' allows you to set the 'this' value now while allowing you to execute the function 
in the future,because it returns a new function object.

Note :
a) 'this' refers to a new Instance.

When a function is invoked with the 'new' keyword,then the function is known as
a constructor function and returns a new instance.In such cases,the value of 'this'
refers to a newly created instance.

ex : 
function Person(fn, ln) {
this.first_name = fn;
this.last_name = ln;

this.displayName = function() {
console.log(`Name: ${this.first_name} ${this.last_name}`);
}
}

let person = new Person("John", "Reed");
person.displayName();  // Prints Name: John Reed
let person2 = new Person("Paul", "Adams");
person2.displayName();  // Prints Name: Paul Adams

b) 'this' refers to an Invoker Object (Parent object)

In javascript, the property of an object can be a method or a simple value.
When an object's method is invoked, then 'this' refers to the object which contains the
method being invoked.

ex :
 function foo () {
'use strict';
console.log("Simple function call")
console.log(this); 
}

let user = {
count: 10,
foo: foo,
foo1: function() {
console.log(this);
}
}

user.foo()               //  “this” refers to user object instead of global object.
let fun1 = user.foo1;
fun1()                  //  this method is invoked as a simple function.
user.foo1()            // As foo1 is invoked as a object’s method

The function definition of 'foo1' is the same,but when it's being called as a 
simple function call,then 'this' refers to a global object.And when the same 
definition is invoked as an object's method,then 'this' refers to the parent 
object.so the value of 'this' depends on how a method is being invoked.

Summary :
1.By default,'this' refers to a global object, which is global in the case of NodeJS and
a 'window' object in the case of a browser.
2.When a method is called as a property of an object, then 'this' refers to the parent object.
3.When a function is called with the 'new' operator , then 'this' refers to the newly created instance.
4.When a function is called using the 'call' and 'apply' methods,then 'this' refers to the value passed 
as the first argument of the call and apply method.

No comments:

Post a Comment