I created a Car (Auto in German) class to simulate the speed of a Car. I want the Ford object to start at 0 and increase its speed every second by 15. For this, I used setInterval. But, when I call the plus() function in setInterval, it gives me back NaN every second. When I just call the method by using Ford.plus();, It works perfectly and gives back an Integer
//require "prompt-sync"
const prompt = require("prompt-sync")({ sigint: true });
//Auto class
class Car{
constructor(brand, speed, maxSpeed, currentSpeed){
this.carBrand = brand;
this.carSpeed = speed;
this.carMaxSpeed = maxSpeed;
this.carCurrentSpeed = currentSpeed;
}
drive(){
if(this.carCurrentSpeed >= this.carMaxSpeed){
clearInterval(inter);
console.log("too fast");
}else{
this.carCurrentSpeed = this.carCurrentSpeed + this.carSpeed;
console.log(this.carBrand + " has a speed of " + this.carCurrentSpeed + " km/h");
}
}
}
//gameloop
for(var i = 0; i < 3; i++){
//infos from usr
let brand = prompt("what brand is your car? ");
let speed = parseInt(prompt("How much speed does your car gain per second? "));
let maxSpeed = parseInt(prompt("what is the maximum speed of your car? "));
//create Object
var usrAuto = new Car(brand, speed, maxSpeed, 0);
let inter =setInterval(function() {
usrAuto.drive.call(usrAuto)
}, 1000);
}