DEV Community

Janice
Janice

Posted on

1

Learn From Mistakes I Made With `this` in JS

Here I'd like to talk about the mistake I made in one of the online assessments for a job interview regarding this in Javascript.

Here's the question - What would be logged from below code?

function Fox(color) {
  this.color = color;
}

Fox.prototype.speak = function () {
  console.log(`I'm ${this.color}`);
};

const myFox = new Fox('blue');
setTimeout(myFox.speak, 1000);
Enter fullscreen mode Exit fullscreen mode

If you were like me, thought it would log "I'm blue", then congrats, you are perfectly wrong! The correct answer is "I'm undefined".

So why did this lose its context? This is because myFox.speak is passed into setTimeout as a function reference only, without the correct calling context. To fix this problem, here are a few ways.

Use arrow function

Arrow function does not have this and it takes the value of this from an outer context. In this case, the outer context refers to myFox.

setTimeout(() => myFox.speak(), 1000)
Enter fullscreen mode Exit fullscreen mode

Use bind

The calling context is bound by using bind.

setTimeout(myFox.speak.bind(myFox), 1000)
Enter fullscreen mode Exit fullscreen mode

Explicitly evoke speak()

setTimeout(function() {
  myFox.speak()
}, 1000)
Enter fullscreen mode Exit fullscreen mode

Takeaway

Ring off the alarm in your brain whenever you see a function containing this is passed as a reference.

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