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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️