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>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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