代码似乎只是在读取值时分配

时间:2018-03-12 20:40:40

标签: javascript datetime if-statement

所以我有这段代码:

var shotTime = this.lastShot;
  shotTime.setMilliseconds(this.lastShot.getMilliseconds() + this.shootGrace);
  console.log(shotTime);
  console.log(new Date);
  console.log(new Date()>shotTime);
  console.log("-------------------------------");
if(new Date()>shotTime){
  console.log("##############################");
  this.lastShot = new Date();
}

这会产生此输出:

Mon Mar 12 2018 20:35:44 GMT+0000 (GMT Standard Time)
 Mon Mar 12 2018 20:35:45 GMT+0000 (GMT Standard Time)
 true
 -------------------------------
 ##############################
 Mon Mar 12 2018 20:35:45 GMT+0000 (GMT Standard Time)
 Mon Mar 12 2018 20:35:45 GMT+0000 (GMT Standard Time)
 false
 -------------------------------
 Mon Mar 12 2018 20:35:46 GMT+0000 (GMT Standard Time)
 Mon Mar 12 2018 20:35:45 GMT+0000 (GMT Standard Time)
 false
 -------------------------------
 Mon Mar 12 2018 20:35:46 GMT+0000 (GMT Standard Time)
 Mon Mar 12 2018 20:35:46 GMT+0000 (GMT Standard Time)
 false
 -------------------------------
 Mon Mar 12 2018 20:35:47 GMT+0000 (GMT Standard Time)
 Mon Mar 12 2018 20:35:50 GMT+0000 (GMT Standard Time)
 true
 -------------------------------
 ##############################

这是相当奇怪的,因为this.lastShot似乎正在改变而false,而它应该只在true时改变。我无法弄清楚为什么会有这种变化。

谢谢,编

1 个答案:

答案 0 :(得分:1)

shotTime = this.lastShot;

执行此操作时,您不会复制。您现在有两个对同一Date对象的引用。更改其中一个引用现在将影响两者。当你改变shotTime时,你也会改变this.lastShot。这样做是为了测试:

var shotTime1 = new Date();
console.log(shotTime1.getMilliseconds());
var shotTime2 = shotTime1;
shotTime2.setMilliseconds(0);
console.log(shotTime1.getMilliseconds());

你会看到第二个是零,因为shotTime1和shotTime2都引用了同一个Date对象。