繁体   English   中英

为什么显示为undefined / NaN?

[英]Why does it show as undefined/ NaN?

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。相反,它显示undefined,之后每秒钟显示为NaN。

我已经尝试过Number()和toString(),以防万一,但是没有用。

您需要将上下文绑定到interval回调方法以保留类上下文。 因此,而不是调用setInterval(this.calcSpeed, 1000); ,请调用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();

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM