HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Understanding the "this" keyword in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
keywordjavascriptunderstandingthisthe

Problem

In JavaScript, the this keyword refers to the object that is currently executing the code. The short version of what this evaluates to is as follows:
  • By default, this refers to the global object.
  • In a function, when not in strict mode, this refers to the global object.
  • In a function, when in strict mode, this is undefined.
  • In an arrow function, this retains the value of the enclosing lexical context's this.

Solution

console.log(this === window); // true


  • In a function, when not in strict mode, this refers to the global object.
  • In a function, when in strict mode, this is undefined.
  • In an arrow function, this retains the value of the enclosing lexical context's this.
  • In an object method, this refers to the object the method was called on.
  • In a constructor call, this is bound to the new object being constructed.
  • In an event handler, this is bound to the element on which the listener is placed.

Code Snippets

console.log(this === window); // true
function f() {
  return this;
}

console.log(f() === window); // true
'use strict';

function f() {
  return this;
}

console.log(f()); // undefined

Context

From 30-seconds-of-code: this

Revisions (0)

No revisions yet.