0

initialSpeed is not being updated, it shows first as undefined and later as NaN.

the start() and calcSpeed() methods work perfectly fine when outside the class.

class Transportation {
   kind: string;
   speed: number;
   initialSpeed: number = 0;

   constructor(kind: string, speed:number) {
     this.kind = kind;
     this.speed = speed;
   }
   start() {
     let begin = setInterval(this.calcSpeed, 1000);
   }
   calcSpeed() {
     console.log("initial speed: ", this.initialSpeed);
    return this.initialSpeed = this.speed + this.initialSpeed;
   }
}

let car = new Transportation("car", 50);
console.log(car);
car.start();

It should show 0 and every second increase by 50. Instead, it shows undefined and every second after that as NaN.

I've tried Number() and toString() just in case but didnt work.

Jojo
  • 65
  • 5
  • Possible duplicate of [setTimeout and "this" in JavaScript](https://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript) – adiga Apr 12 '19 at 12:30

2 Answers2

2

You need to bind the context to the interval callback method to preserve the class context. So instead of calling setInterval(this.calcSpeed, 1000);, call setInterval(this.calcSpeed.bind(this), 1000);

class Transportation {
   kind: string;
   speed: number;
   initialSpeed: number = 0;

   constructor(kind: string, speed:number) {
     this.kind = kind;
     this.speed = speed;
   }
   start() {
     let begin = setInterval(this.calcSpeed.bind(this), 1000);
   }
   calcSpeed() {
     console.log("initial speed: ", this.initialSpeed);
    return this.initialSpeed = this.speed + this.initialSpeed;
   }
}

let car = new Transportation("car", 50);
console.log(car);
car.start();
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
  • Yes, of course. I'm very new at this....I dont know how to do it but I will find out right away! It says I can accept it in 5 minutes – Jojo Apr 12 '19 at 12:34
1

Move start function outside Transportation class and pass car object to it like this and it will work:

class Transportation {
   kind: string;
   speed: number;
   initialSpeed: number = 0;

   constructor(kind: string, initialSpeed:number, speed:number) {
     this.kind = kind;
     this.speed = speed;
     this.initialSpeed = initialSpeed
   } 

    calcSpeed(car: Transportation) {   
      console.log("initial speed: ", car.initialSpeed);     
      car.initialSpeed += car.speed    
    }

}

function start(car: Transportation) {
  let begin = setInterval(car.calcSpeed, 1000, car);
}

let car = new Transportation("car", 0 , 50);
console.log(car);
start(car);
Roland
  • 54
  • 2