0

       var Car = function(x,y){
           this.x = x,
           this.y = y
       };
       Car.prototype.draw = function(){
        var 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);
       };

       Car.prototype.moveRight = function (){
           this.x +=5;
            this.carElement.css({
               left: this.x,
               top: this.y
           });


       };
       var tesla = new Car(10,20);
       var nissan = new Car (100,200);


        tesla.draw();
        nissan.draw();
       setInterval(nissan.moveRight(),2000);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OOP</title>
</head>
<body>
    <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
</body>
</html>

1
  • setInterval(()=>nissan.moveRight(),2000) 10 апр 2021 в 9:21

1 ответ 1

0

внутри setInterval нужно передать функцию, и ей задать уже числовой интервал. Немного поправил Ваш код по дороге.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OOP</title>
</head>
<body>
<script
        src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
        integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
        crossorigin="anonymous"></script>
</body>
</html>

<script>
    $(function() {
        let Car = function(x,y){
            this.x = x,
            this.y = y
        };

        Car.prototype.draw = function(){
            this.carElement = $('<img src="http://nostarch.com/images/car.png">');
            this.carElement.css({
                position: "absolute",
                left: this.x,
                top: this.y
            });
            $("body").append(this.carElement);
        };

        Car.prototype.moveRight = function (speed){
            this.x += speed;
            this.carElement.css({
                left: this.x,
                top: this.y
            });
        };

        let tesla = new Car(10,20);
        let nissan = new Car(100,200);

        tesla.draw();
        nissan.draw();

        setInterval(() => {
            tesla.moveRight(5)
            nissan.moveRight(10)
        },100);
    });
</script>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.