DEV Community

Cover image for JS interview in 2 minutes / this 🤯
Nick K
Nick K

Posted on

JS interview in 2 minutes / this 🤯

Question:
Explain this keyword in JavaScript.

Quick answer:
this keyword is referencing the current execution context.

Longer answer:
this works differently depending on where it was called.

If you use this in the global context, it will reference the window object in the browser and the global object in the node.

// browser
console.log(window.a) // undefined
this.a = 1
console.log(window.a) // 1

// node
console.log(global.a) // undefined
this.a = 1
console.log(global.a) // 1
Enter fullscreen mode Exit fullscreen mode

For functions, it works similarly, but a still bit differently for the strict mode.

function f1() {
  return this // default to global context
}

function f2() {
  'use strict';
  return this // undefined
}
Enter fullscreen mode Exit fullscreen mode

Arrow functions have their own tricks as well, they always refer to enclosing this. We will get into details in the next section.

let f1 = function() {
  return this
}

let f2 = () => this

console.log(f1(), f2()) // Window, Window

let obj = { f1, f2 }
console.log(obj.f1(), obj.f2()) // obj reference, Window
// ^^^ f1 changed reference, but f2 didn't
Enter fullscreen mode Exit fullscreen mode

As for the class context, this refers object itself

class Tmp {
  a = 10
  method() {
    console.log(this)
  }
}
let tmp = new Tmp()
tmp.method() // Tmp {a: 10}
Enter fullscreen mode Exit fullscreen mode

Feels like these are the most popular cases, but there are much much more corner cases, take a look on mdn.

Real-life applications:

I think one of the most common caveats with this is when you are using callbacks, which are popular in React and in Angular as well.

class User {
  _say(text) {
    console.log(text)
  }

  sayHello() {
    this._say('Hello world')
  }

  sayHi = () => this._say('Hi!')
}

let user = new User()

user.sayHi() // Works
user.sayHello() // Works

setTimeout(user.sayHi, 1000) // Works

// callback will show an error, because `this` reference will change
// Uncaught TypeError: this._say is not a function at sayHello
setTimeout(user.sayHello, 1000)
Enter fullscreen mode Exit fullscreen mode

So be careful and stay safe!

Resources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Other posts:


Btw, I will post more fun stuff here and on Twitter. Let's be friends 👋

Top comments (2)

Collapse
 
rb_wahid profile image
Raihan Bin Wahid

This is awesome. And can be more awesome if you create a series for multiple posts. 😊

Collapse
 
hexnickk profile image
Nick K • Edited

Thanks! I'm trying to post an article per day, so there are some already! 😉
dev.to/kozlovzxc