为什么显示为undefined / NaN?

时间:2019-04-12 12:25:49

标签: javascript typescript class oop

initialSpeed没有被更新,它首先显示为undefined,然后显示为NaN。

start()和calcSpeed()方法在类之外时可以很好地工作。

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

它应该显示0,并且每秒增加50。 而是显示未定义,其后每秒显示为NaN。

为了防止万一,我尝试了Number()和toString(),但没有用。

2 个答案:

答案 0 :(得分:2)

您需要将上下文绑定到interval回调方法以保留类上下文。 因此,不用致电invalid_gender = True while invalid_gender: gender = input('Please Enter Student Gender (M or F):') if gender.upper() not in ['M', 'F']: print('Invalid gender! Please, try again.') else: invalid_gender = False ,而是致电setInterval(this.calcSpeed, 1000);

setInterval(this.calcSpeed.bind(this), 1000);

答案 1 :(得分:1)

将启动功能移到交通运输类之外,然后将汽车对象传递给它,它将起作用:

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