2011-11-09 180 views
1

我剛剛開始使用dateJS,它似乎是一個很好的lib,但我顯然錯過了一些東西(可能是一個愚蠢的錯誤),但在我的函數中,我需要3個日期:clickedDate,weekStart & weekEnd。但使用dateJS我似乎覆蓋每個變量。有人能指出我的錯誤嗎?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)} 
+2

[SSCCE](http://sscce.org)。一個很棒的JavaScript SSCCE工具:http://jsfiddle.net。什麼是'myDate',一個字符串?順便說一句,你是否想'console.log(clickDate)'連續兩次? –

+0

[It works for me](http://jsfiddle.net/LJJKn/)。 –

+0

使用更多全局變量 –

回答

3

這不是Datejs問題,但JavaScript的Date對象的特徵(?)。在JavaScript中,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是 「克隆」 的日期對象的方式。以下示例演示在'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」發生了變化。

希望這會有所幫助。

+3

Javascript * Date是可變的*,並非如所述的不可變。這是一個參考類型,是正確的。但是引用與值類型是一個方面,而可變性則是完全不同的東西。如果一切都很好,那麼Date就是(1.)不變的(2.)值類型,就像在.Net中一樣。 – citykid