Published on

Use of `this` Keyword in Javascript.

  • avatar
    Md Rathik

Javascript this

Img Credit : sydney Rae

This is one of the most common questions in Javascript interviews. In general, the “this” keyword refers to an object depending on the situation and its uses.

  • this refers to an object when it’s into the object method.
  • this refers to the global object when it’s alone.
  • this with strict mode, its “undefined”
  • this refers to the element as this when receiving the event.
  • this refers to any object when use methods like call() , apply() & bind() can refer

Use in Method

let Country = {
  name: 'Bangladesh',
  sayName: function () {
    console.log( //Bangladesh

Copy the code and run,

You will see, that its prints the country name, which is the property of the Country object. That means in the method this will reference its object.

Use thisin Global Scope or in function alone

console.log(this) //widnow object
function getThis() {
  console.log(this) //widnow object

If you run this code, you will see both of them are referring to the global/window object.

Use this in “Strict” Mode.

'use strict'
console.log(this) //widnow object

function myFunction() {
  return this
console.log(myFunction()) //undefined

In Strict mode when this assign in global scope, it will refer to the global object.

But when its assign in function with strict mode, it will undefined.

This with event handler

button onclick="'none'">Click to Remove Me!</button>

Just run this code and click on button, it will remove as display none. that means when the event happening this is referring to itself.

This with call() function

const person1 = {
  fullName: function () {
    return this.firstName + ' ' + this.lastName

const person2 = {
  firstName: 'John',
  lastName: 'Doe',

let x =
console.log(x) //John Doe

In this example, we can see in person1 this working as persob2 object. cause when we call the fullname from person1 , we call person2 to as this. That’s why person is reffer to the this.

apply() & bind() are works also similar to call(). if you are clear with this example, hope you will try these function yourself.