Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,954 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.