0

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
  • No, the `.bind(`…`)` goes after the `var teslaMove = tesla.moveRight` and `var nissanMove = nissan.moveRight`. You want to bind those methods, not some random properties that aren’t reachable to begin with. This is already explained in the linked Q&A and in the [documentation](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). Also, ignore the answer below; it’s been generated by ChatGPT, which is [banned](/help/gpt-policy) on Stack Overflow. – Sebastian Simon Jan 21 '23 at 05:10

0 Answers0