[英]dateJS is overwriting variables
我刚开始使用dateJS,它看起来像一个很棒的lib,但我显然错过了一些东西(可能是一个愚蠢的错误),但在我的函数中我需要3个日期:clickedDate,weekStart和weekEnd。 但是使用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)}
这不是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'和' .clone()
对象上使用.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
运行上述操作,即使'a'发生了变化,您也应该看到'b'和'c'的最终结果仍然反映了它们的原始值。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.