DEV Community

Janice
Janice

Posted on

`this` Used In Objects

this is one of the most tricky concepts in JavaScript. Fully understanding this topic sets us apart from the other devs in job interviews.

Previsouly I wrote a post Learn From Mistakes I Made With this in JS, which is about handling this used in a function passed as a reference to another function. Here is a continued part talking more about this when it's used with objects. Here's an example:

function makeFox() {
  return {
    name: 'fox',
    ref: this
  }
}

const fox = makeFox();
fox.ref.name // what's the result?
Enter fullscreen mode Exit fullscreen mode

The code results in an error calling .name on undefined. This is because this refers to the context of the function makeFox, not the object returned from it. Here's a way to fix this problem:

function makeFox() {
  return {
    name: 'fox',
    ref() {
        return this;
    }
  }
}

const fox = makeFox();
fox.ref().name // 'fox'
Enter fullscreen mode Exit fullscreen mode

By making ref a function, this becomes dynamic. Its value depends on the object which evokes this function. In this case, the calling object is fox.

Takeaway

Ring off the alarm in your brain once you see this is exposed without being wrapped within a code block as a property of an object. For example,

let obj = {
  prop: this
}
Enter fullscreen mode Exit fullscreen mode

Chances are a mistake has been made unconciously.

Top comments (0)