1

Когда я в консоли использую ранее созданные в самом HTML-файле методы moveRight или moveDown, то они работают как надо, а вот moveLeft и moveUp, не работают. Консоль возвращает not a function. Хотя я уже всё копировал под чистую с учебника. По учебнику вводя в консоли tesla.moveUp(); элемент должен двигаться вверх, но этого не происходит.

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 }); };

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

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

var tesla = new Car(20, 20); var nissan = new Car(100, 200); tesla.draw(); nissan.draw();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
ThisMan
  • 12,261

1 Answers1

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 }); };

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

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

var tesla = new Car(200, 20); var nissan = new Car(100, 200); tesla.draw(); nissan.draw();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button onclick="tesla.moveLeft()">Left</button>
  <button onclick="tesla.moveRight()">Right</button>
  <button onclick="tesla.moveUp()">Up</button>
  <button onclick="tesla.moveDown()">Down</button>
  <br/>
  <br/>
</div>