为什么这个 Javascript 函数调用两次就不起作用?

Why does this Javascript function not work if called twice?

Jasmine(单元?)测试我 运行 适用于我下面代码的所有测试,但最后一个测试调用 Gigasecond.date() 两次,然后验证第二个,哪个失败。

var Gigasecond = function(date) {
    this.startDate = date;
};

Gigasecond.prototype.date = function() {
    var x = this.startDate;
    x.setSeconds(x.getSeconds() + 1000000000);
    return x;
    }

module.exports = Gigasecond; 

我想我不知道为什么会失败。当我登录到控制台时,我看到日期增加了两次,但认为 x 是它自己的单独变量,每次调用函数时都会获得 created/destroyed ..但似乎不是。 x 只是对对象上实际 .startDate 字段的引用吗?是否有关于其工作原理的任何参考 material?我环顾四周,但找不到任何适用于这段代码中发生的事情的东西。

你声明你

thought that x is its own separate variable that gets created/destroyed each time the function is called.. but it seems not. Is x just a reference to the actual .startDate field on the object?

没错。日期是对象,在 JavaScript 中,对象通过引用分配给变量,而不是复制。如果您打算使用一个副本,您需要先 return 使用 new Date(dateToBeCopied.getTime()) 克隆 Date 对象。

在你的代码中,如果你想处理日期的副本,你需要替换行

var x = this.startDate; //assignment by reference

用这条线

var x = new Date(this.startDate.getTime()); //assignment by copy

下面的示例代码演示了这是如何工作的。日期对象 dateA 通过引用分配给变量 refA,通过复制分配给变量 copyA。当修改 refA 时,这会影响 dateA,而 copyA 不受影响。

var dateA = new Date();

//assign a reference to dateA
var refA = dateA;

//assign a copy of dateA
var copyA = new Date(dateA.getTime());

//modify refA, increment with one year
refA.setFullYear(refA.getFullYear() + 1);

//variable refA points to dateA,
//both show the date incremented with one year
console.log('+1 year: ', dateA);
console.log('+1 year: ', refA);

//variable copyA returns an unmodified copy,
//not incremented
console.log('unmodified copy: ', copyA);