Javascript 递减值 returns NaN

Javascript decrementing value returns NaN

你好,我正在开发一个小型 JS 循环,它每隔 X 秒在一个范围内随机选择一个动作,这是我当前的脚本:

var test = {
    lastFrame: 0,
    timeBeforeSomething: 0.0,
    
    update: function() {
        let now = Date.now();
        
        if( this.lastFrame != undefined ) {
            let delta = ( now - this.lastFrame ) / 1000;
            
            if( this.timeBeforeSomething <= 0 ) {
                this.doSomething();
                
                this.timeBeforeSomething = Math.round( ( ( Math.random() * ( 1.0 - 0.5 ) ) + 0.5 ) * 1000 ) / 1000;
                console.log( 'this.timeBeforeSomething = ' + this.timeBeforeSomething );
            } else {
                this.timeBeforeSomething -= delta;
                console.log( 'this.timeBeforeSomething -= ' + delta + ' => ' + this.timeBeforeSomething );
            }
        }
        
        this.lastFrame = now;
        
        setTimeout( test.update, 0 );
    },
    
    doSomething: function() {
        console.log( 'something' );
    }
}

test.update();

我的问题来自 timeBeforeSomething 属性,实际上这个在第二个循环中设置为 NaN。

但我只是:给它赋浮点值,然后减值,所以我不明白为什么。

这里是这个脚本打印的痕迹:

something
this.timeBeforeSomething = 0.672
this.timeBeforeSomething -= 0.01 => NaN
this.timeBeforeSomething -= 0.004 => NaN
this.timeBeforeSomething -= 0.012 => NaN
this.timeBeforeSomething -= 0.013 => NaN
this.timeBeforeSomething -= 0.015 => NaN

从那里开始,timeBeforeSomething 保持等于 0.672,你知道为什么吗?

您需要 bind 您对 test.update 的调用到当前 this 上下文。否则它将获得函数的 this 上下文,其中 timeBeforeSomething 未定义:

setTimeout(test.update.bind(this), 1000);

完整片段:

var test = {
  lastFrame: 0,
  timeBeforeSomething: 0.0,

  update: function() {
    let now = Date.now();

    if (this.lastFrame != undefined) {
      let delta = (now - this.lastFrame) / 1000;

      if (this.timeBeforeSomething <= 0) {
        this.doSomething();

        this.timeBeforeSomething = Math.round(((Math.random() * (1.0 - 0.5)) + 0.5) * 1000) / 1000;
        console.log('this.timeBeforeSomething = ' + this.timeBeforeSomething);
      } else {
        this.timeBeforeSomething -= delta;
        console.log('this.timeBeforeSomething -= ' + delta + ' => ' + this.timeBeforeSomething);
      }
    }

    this.lastFrame = now;

    setTimeout(test.update.bind(this), 1000);
  },

  doSomething: function() {
    console.log('something');
  }
}

test.update();