Estoy tratando de ejecutar un método de objeto 'Car' en la ventana del navegador con 'setInterval' pero solo funciona una vez. ¿Cuál es el problema de mi código? Además, estoy confundido si ponemos la función en setInterval con paréntesis o sin él.
Aquí está mi código:
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>Estás perdiendo la referencia a this variable. Vincularlo al objeto
setInterval(classicCar.moveRight.bind(classicCar), 1000);