DEV Community

Janice
Janice

Posted on

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.

Top comments (0)