I am trying to make an animation of image moving, it is worked when I input the moving function manually, however it doesn't work when put it into the setInterval function which producing the error as the title mentioned:
`
<script>
let Car = function (x,y) {
this.x = x;
this.y = y;
};
Car.prototype.draw = function () {
const carHtml = '<img src='http://nostarch.com/images/car.png'>';
this.carElement = $(carHtml);
this.carElement.css({
position: "absolute",
left: this.x,
top: this.y
});
$("body").append(this.carElement);
};
var tesla = new Car(20,50);
var nissan = new Car(100, 200);
tesla.draw();
nissan.draw();
Car.prototype.moveRight = function () {
this.x += 5;
this.carElement.css({
left: this.x,
top: this.y
});
};
var teslaMove = tesla.moveRight;
var nissanMove = nissan.moveRight;
setInterval(teslaMove, 10);
setInterval(teslaMove, 10);
</script>
`
When I input tesla.moveRight() in the console of browser manually, it can move once; However, when I use setInterval to run, it shows the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'css') at Car.moveRight (drawCarProto.html:34:33)
Update I have tried to add .bind in three ways but it still doesn't work
//1. add .bind behind the function of css
Car.prototype.moveRight = function () {
this.x += 5;
this.carElement.css({
left: this.x,
top: this.y
}).bind;
}; // Uncaught TypeError: Cannot read properties of undefined
(reading 'css') at Car.moveRight
//2. add .bind behind this.carElement.css
Car.prototype.moveRight = function () {
this.x += 5;
this.carElement.css.bind({
left: this.x,
top: this.y
});
}; // Uncaught TypeError: Cannot read properties of undefined
(reading 'css') at Car.moveRight
//3. add .bind behind the prototype function
Car.prototype.moveRight.bind = function () {
this.x += 5;
this.carElement.css({
left: this.x,
top: this.y
});
}; //Uncaught TypeError: Cannot set properties of undefined
(setting 'bind') at drawCarProto.html:32:34