dateJS正在覆盖变量

时间:2011-11-09 19:25:14

标签: javascript datejs

我刚开始使用dateJS,它看起来像一个很棒的lib,但我显然错过了一些东西(可能是一个愚蠢的错误),但在我的功能中我需要3个日期:clickedDate,weekStart&周末。但是使用dateJS我似乎在覆盖每个变量。有人可以指出我的错误吗?

var clickDate = myDate;
    console.log(clickDate);
var weekStart = Date.parse(clickDate).last().monday();
    console.log(clickDate);
var weekEnd = Date.parse(clickDate).next().sunday();
    console.log(weekEnd);

console.log('break');   

console.log(clickDate);
console.log(weekStart);
console.log(weekEnd);

控制台显示以下内容

Date {Wed Nov 30 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Mon Nov 28 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
break
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}

1 个答案:

答案 0 :(得分:3)

这不是Datejs的问题,而是JavaScript Date对象的一个​​功能(?)。在JavaScript中,Date对象是可变的,将Date对象值设置为新变量会创建对原始对象的引用,而不是新对象。

这可以使用普通的旧JavaScript(没有Datejs)来演示:

<强>〔实施例

var a = new Date(2011, 0, 1);
var b = a;
var c = b;

console.log('a', a); // 1-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011

// setting only 'a' will cause 'b' and 'c' to update as well.
a.setDate(10);

console.log('a', a); // 10-Jan-2011
console.log('b', b); // 10-Jan-2011
console.log('c', c); // 10-Jan-2011

如果使用Datejs,解决这个问题的方法是“克隆”Date对象。以下示例演示了在'b'和'c'Date对象上使用.clone()函数。

示例

var a = new Date(2011, 0, 1);
var b = a.clone(); // clone creates a new 'copy' of 'a'.
var c = b.clone();

console.log('a', a); // 1-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011

a.setDate(10);

console.log('a', a); // 10-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011

运行上述内容,您应该看到“b”和“c”的最终结果仍然反映其原始值,即使“a”已更改。

希望这有帮助。