Hello. I write the code for the book, I wrote everything as there. Then they gave the task to animate the machine with setInterval. But they only move once by 5 pixels, but they should every 30 miles-seconds.

$(document).ready(function(){ var Car = function (x, y) { this.x = x; this.y = y; }; Car.prototype.draw = function() { var carImg = '<img src="img/logo.jpg" style="width: 100px; height: 100px;">'; this.carElement = $(carImg); this.carElement.css({ position: "absolute", left: this.x, top: this.y }); $('body').append(this.carElement); }; Car.prototype.moveRight = function() { this.x += 5; this.carElement.css ({ left: this.x, top: this.y }); }; var nissan = new Car(100, 100); var kia = new Car(200, 200); nissan.draw(); kia.draw(); setInterval(nissan.moveRight(), 20); setInterval(kia.moveRight(), 30); }); 

    1 answer 1

    here:

     setInterval(nissan.moveRight(), 20); setInterval(kia.moveRight(), 30); 

    you call methods immediately, but you need to pass a link to them:

     setInterval(nissan.moveRight, 20); setInterval(kia.moveRight, 30); 

    And there will most likely be a loss of context. To which he will change, his example and how to deal with it can be found here , as well as the full answer here.

    • then this error goes: Uncaught TypeError: Can't read property 'css' of undefined at Car.moveRight (script.js: 35) - Horchynskyi
    • @Horchynskyi added ... in the first link a similar problem, in the second - a full description of this problem - Alexey Shimansky