0

I'm trying to run a 'Car' object method across the browser window with 'setInterval' but it only work once. What's the problem of my code? Also, I am confused if we put the function in setInterval with parenthesis or without it?

Here is my code:

var Car = function(x, y) {
  this.x = x;
  this.y = y;
  //   drawing in constructor
  this.draw();
};
Car.prototype.draw = function() {
  var carhtml =
    '<img src="https://www.pngitem.com/pimgs/m/195-1953962_vector-vintage-classic-car-free-hd-image-clipart.png">';

  this.carElement = $(carhtml);
  this.carElement.css({
    position: "absolute",
    left: this.x,
    top: this.y,
    width: 400,
  });
  $("body").append(this.carElement);
};
Car.prototype.moveRight = function() {
  this.x += 10;
  this.carElement.css({
    left: this.x,
    top: this.y,
  });
};
var classicCar = new Car(0, 100);
setInterval(classicCar.moveRight, 1000);
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>

4
  • 1
    developer.mozilla.org/en-US/docs/Web/API/… Commented Jan 3, 2022 at 9:37
  • 2
    Hello there Hy Lai. Welcome to StackOverflow. Your code is working perfectly. The car Object simply moves off the right-hand side of the screen and keeps going! If this is not what you want please edit your question to explain exactly what you would like to happen. Commented Jan 3, 2022 at 9:39
  • @BrianPeacock The code gives error due to this not being what OP thinks it is Commented Jan 3, 2022 at 9:43
  • @mplungjan Which this do you mention? Commented Jan 3, 2022 at 9:49

1 Answer 1

2

You are losing the reference to the this variable. Bind it to the object

setInterval(classicCar.moveRight.bind(classicCar), 1000);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this works! I will go and find out thebind functions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.