DEV Community

vishwa@chauhan
vishwa@chauhan

Posted on

this in javascript ?

In javascript this keyword can have different values in non-strict and strict mode. The value of this depends in which context it appears like, function, global, class

First we'll explore this in function context

function whatsThis() {
  return this;
}
console.log(whatsThis() === globalThis);// true

const detailObj = {
  name: 'vishwa'
};

detailObj.whatsThis = whatsThis;
console.log(detailObj.whatsThis() === detailObj); // true
Enter fullscreen mode Exit fullscreen mode

the value of this depends on how function is called, In first console whatsThis is accessed on globalThis so the value of this is globalThis, In second console whatsThis is accessed on detailObj so the value of this is detailObj.
So the value of this is the object that is used to call the function.

In strict mode if function is accessed on globalThis the value of this is undefined.

function whatsThis() {
  'use strict'
  return this;
}
console.log(whatsThis() === undefined);// true
Enter fullscreen mode Exit fullscreen mode

Arrow functions:
In arrow functions this retains the value of it's enclosing lexical context this, arrow functions create the closure over the this value of it's surrounding scope. so no matter how function is invoked the value of this is same what it was when the function was created.

const arrowFunc = () => this;

console.log(arrowFunc() === globalThis);

const obj = {
  name: 'vishwa'
};

console.log(arrowFunc.call(obj) === globalThis); //true 
Enter fullscreen mode Exit fullscreen mode

Constructors:
when a functions is used as a constructor it's this is bound to the new object created. The value of this becomes the value of the new expression unless the constructor returns another non-primitive value.

function getInfo() {
  this.name = 'vishwa';
  this.job = 'coding';
}

const detail = new getInfo();

console.log(detail); //{"name": "vishwa",  "job": "coding"}

function getInfo2() {
  this.name = 'vishwa';
  return {id: 100};
}

const detail2 = new getInfo2();

console.log(detail2); //{"id": 100}
Enter fullscreen mode Exit fullscreen mode

Class:
Class constructors are always called with new, so their behaviour is same as function constructors.

class Detail{
    constructor() {
        this.name = 'vishwa';
        this.job = 'coding';
    }
}

const detail = new Detail();

console.log(detail); // {name: 'vishwa', job: 'coding'}
Enter fullscreen mode Exit fullscreen mode

bind method
Calling bind on function f, creates a new function with the same body as function f, but the value of this is bound to the first argument of bind.

function f() {
  return this.a;
}

const obj = {
  a: 'pop'
};

const binded = f.bind(obj);

console.log(binded()); // 'pop'
Enter fullscreen mode Exit fullscreen mode

this in DOM event handlers:
When a function is used as a eventlistener it's this value is bound to the element on which eventlistenter is placed

Top comments (0)