Skip to content

What is THIS in Javascript

Drew Knowles edited this page Feb 4, 2024 · 1 revision

What is THIS in javascript?

This is a reference to the object that is calling the current function

If the function is a method in a object, this refers to the object that is calling the method

If the function is not associated to an object then it refers to the global object which is the window object and object.

const video = {
title: 'a'
play() {
  console.log(this);
  }
}

video.stop = function() {
   console.log(this);
};

video.stop()

// Prints { title: 'a', play: f, stop: f} 
// Prints the video object

If we use a regular function

const video = {
title: 'a'
play() {
  console.log(this);
  }
}

function playVideo() {
  console.log(this);
}

playVideo();

// Prints Window(postMessage: f, blur: f, focus: f, close: f, frames: f)

The this operator basically meaning getting access to the object that is calling the current function.

Clone this wiki locally