DEV Community

Cover image for Understanding `this` keyword in javascript
Royal Jain for CodeParrot

Posted on

14 2 2 3 2

Understanding `this` keyword in javascript

The this keyword in JavaScript is a reference to the object that is currently executing or invoking the current method or function. It is a context-specific keyword, meaning its value changes depending on where and how it is used within your code.

Let's see how this behaves in different contexts:

Global Context

When used outside of any function, this refers to the global object. In a browser environment, the global object is window,

console.log(this === window); // true in a browser environment
Enter fullscreen mode Exit fullscreen mode

whereas in Node.js, it's called global.


// Define a global variable
global.myGlobalVar = 'Hello, global!';

// Use a built-in global function
setTimeout(() => {
  console.log(myGlobalVar); // Access the global variable without using 'global.' prefix
}, 1000);

// Access a global object property: process
console.log('Current version of Node.js:', process.version);

Enter fullscreen mode Exit fullscreen mode

Function Context

In a regular function call, this refers to the global object (non-strict mode) or is undefined (strict mode).

function myFunction() {
  console.log(this);
}
myFunction(); // logs global object (window in browsers) or undefined in strict mode


/*node.js*/
function testFunction() {
  return this === global;
}

console.log(testFunction()); // true
Enter fullscreen mode Exit fullscreen mode

Inside a method (a function inside an object), this refers to the object the method was called on.


const myObject = {
  myMethod() {
    console.log(this);
  }
};
myObject.myMethod(); // logs myObject

Enter fullscreen mode Exit fullscreen mode

Arrow Functions

Arrow functions do not have their own this. Instead, they inherit this from the surrounding (lexical) context. This makes arrow functions particularly useful when you want to ensure that this within a function refers to the surrounding object.


const myObject = {
  myMethod: () => {
    console.log(this);
  }
};
myObject.myMethod(); // logs global object or undefined in strict mode, because arrow functions do not bind their own this
Enter fullscreen mode Exit fullscreen mode

Event Handlers

In the context of DOM event handlers, this refers to the element that received the event, unless an arrow function is used or the function is bound to a different context.


document.getElementById('myButton').addEventListener('click', function() {
  console.log(this); // refers to the element that was clicked
});

Enter fullscreen mode Exit fullscreen mode

Using call(), apply(), and bind() Methods:

JavaScript provides these methods to explicitly set the value of this for any function call. call() and apply() invoke the function immediately with a specified this value, while bind() returns a new function with this bound to a specific object.


function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = { name: 'John' };
greet.call(person); // Hello, John

Enter fullscreen mode Exit fullscreen mode
function greet() {
  console.log(this.message);
}

const friendlyGreet = {
  message: 'Hello, friend!'
};

const strangerGreet = {
  message: 'Hello, stranger.'
};

// Using bind() to create a new function where `this` is set to friendlyGreet
const greetFriend = greet.bind(friendlyGreet);
greetFriend(); // Outputs: Hello, friend!

// Similarly, binding greet to strangerGreet
const greetStranger = greet.bind(strangerGreet);
greetStranger(); // Outputs: Hello, stranger.
Enter fullscreen mode Exit fullscreen mode

Understanding this can be tricky but is important, especially when dealing with object-oriented programming concepts, event handling, and functional programming patterns.

Now, if you understood this well. What do you think will be the output here?

var length = 10;
function fn() {
    console.log(this.length);
}

var obj = {
  length: 5,
  method: function(fn) {
    fn();
    arguments[0]();
  }
};

obj.method(fn, 1);
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (6)

Collapse
 
kresli profile image
Eduard Jacko

Nice. I would also mention difference between globalThis, global and window. But otherwise pretty well done

Collapse
 
royaljain profile image
Royal Jain

Thanks. Can you elaborate on this?

Collapse
 
sakshamverma profile image
SAKSHAM VERMA • Edited

globalThis, global, and window are basically the terms used in the context of different programming environments, particularly in our Js. Each of them refers to the global object in various contexts.
The explaination by Royal Jain is up to mark and one needs to know only content provided by Jain.
Apart from only development if you really enjoy the engineering side of this keyword then it would be a great providing the juicy information.
Btw I suck at writing you can always give constructive criticism on my writing skill to improve it.
Thanks,

Collapse
 
kresli profile image
Eduard Jacko
Collapse
 
idanref profile image
Idan Refaeli

Nice refresher!

Collapse
 
meysam267 profile image
Sana

thank you

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay