DEV Community

Janice
Janice

Posted on

1

`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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay