Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Rizwan Renesa
Rizwan Renesa
7,805 Points

A JavaScript question

I have written this code :

<html>
<body>
<div id ="status">0</div>
<script>
function Car(){
  this.speed = 0;

  setInterval(function(){
    this.speed++;
    document.getElementById("status").innerHTML=this.speed;
  }, 300);
}
var car1 = new Car();
</script>
</body>
</html>  

I already know how to fix this, code below but I don't get it. Can someone please help to explain?

  <html>
<body>
<div id ="status">0</div>
<script>
function Car(){
  this.speed = 0;
  var self=this;
  setInterval(function(){
    self.speed++;
    document.getElementById("status").innerHTML=self.speed;
  }, 300);
}
var car1 = new Car();
</script>
</body>
</html>

1 Answer

Steven Parker
Steven Parker
228,978 Points

It's a matter of scope.

Inside Car, "this" will contain a reference to the class instance, but when the interval callback runs, that's no longer true.

But in the second example, the variable "self" has function scope, and will still have the same value when the callback runs.