This in JavaScript

Kanchanabj
1 min readFeb 1, 2021

To access the object, a method can use this keyword

The value of this is the object “before dot”, the one used to call the method.

It also behaves differently in strict mode and non strict mode.

  1. this in a Method: in an object method, this refers to the “owner” of the method.

const me = {

stName: ‘hema’,

ndName: ‘kun’,

fullName: function(){

return’${this.stName} ${this.ndName}’

}

}

console.log(me.fullName())

  • this refers to me object , because the me object “owns” the fullName method.

2 . this Alone: When used alone, the owner is the global object, so this refers to the Global object.

let thisAlone = this

//In a browser window

console.log(this); //refers to the window object

3.this in a function: Inside function the value of this depends on how the function is being called.

In function, this refers to the global object[object window].

function test(){

return this

}

test() //[object window]

4.this in Function ‘strict mode’

JavaScript strict mode does not allow default binding.

When used in a function, in strict mode, this is undefined.

“use strict”

function test(){

return this

}

test() //undefined.

5.Inside Arrow Function

Arrow function are special they do not have their own this

In arrow functions this retains the value of enclosing lexical context this

let user = {

firstName: “Joe”,

sayHi(){

let arrow=()=>alert(this.firstName);

arrow();

}

};

user.sayHi();

This is the special feature of arrow function. This is useful when we don not want to have separate this but want to take from outer context.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response