Understanding `this` keyword in javascript

Royal Jain - Feb 10 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .