Skip to main content

This keyword

In JavaScript, this keyword refers to the object to which it belongs. It has different values depending on where it is used.

  • Alone, this refers to the global object
console.log(this) // window
  • In a function with a strict mode, this equals an undefined
"use strict"
function fn() {
console.log(this); // undefined
}
  • In a function, this refers to the global object
function fn() {
return this;
}
console.log(fn()); // window in non-strict mode, undefined in strict mode
  • In an arrow function, this refers to the parent scope
const fn = () => {
console.log(this); // window. Takes this from parent scope
}
  • In an object method , this refers to the object
const obj = {
name: "hello",
fn: function () {
console.log(this.name);
},
};
obj.fn(); // hello