2016-08-01 167 views
2

我正在編寫一個原型函數,它從對象中獲取一個日期,然後向它添加一個gigasecond(100億秒)。這裏是我的代碼:JavaScript:在不改變引用對象鍵的情況下複製對象鍵值

var Gigasecond = function(userDate){ 
    this.userDate = userDate; 
} 

Gigasecond.prototype.date = function(){ 
    var gigaDate = this.userDate; 
    var gigaSecond = Math.pow(10, 9); 

    console.log("This is the first console log: " + this.userDate); 

    //adding the billion seconds to the date 
    gigaDate.setFullYear(gigaDate.getFullYear() + Math.floor(gigaSecond/31536000)); 
    gigaDate.setDate(gigaDate.getDate() + Math.floor((gigaSecond % 31536000)/86400)); 
    gigaDate.setHours(gigaDate.getHours() + Math.floor(((gigaSecond % 31536000) % 86400)/3600)); 
    gigaDate.setMinutes(gigaDate.getMinutes() + Math.floor((((gigaSecond % 31536000) % 86400) % 3600)/60)); 
    gigaDate.setSeconds(gigaDate.getSeconds() + (((gigaSecond % 31536000) % 86400) % 3600) % 60); 

    console.log("this should equal the first console log: " + this.userDate); 
} 

日期進入this.userDateSunday, Sep 13, 2015 18:00。我想保留this.userDate完整的功能的另一部分。問題是,當我更改gigaDate時,它也會更改this.userDate。這裏是控制檯輸出:

This is the first console log: Sun Sep 13 2015 18:00:00 GMT-0600 (MDT) this should equal the first console log: Thu May 30 2047 19:46:40 GMT-0600 (MDT)

任何提示?

回答

1

您想創建一個新的日期對象,而不是簡單地將其分配給另一個對象。

var Gigasecond = function(userDate){ 
    this.userDate = userDate; 
} 

Gigasecond.prototype.date = function(){ 
    var gigaDate = new Date(this.userDate); 
    var gigaSecond = Math.pow(10, 9); 

    console.log("This is the first console log: " + this.userDate); 

    //adding the billion seconds to the date 
    gigaDate.setFullYear(gigaDate.getFullYear() + Math.floor(gigaSecond/31536000)); 
    gigaDate.setDate(gigaDate.getDate() + Math.floor((gigaSecond % 31536000)/86400)); 
    gigaDate.setHours(gigaDate.getHours() + Math.floor(((gigaSecond % 31536000) % 86400)/3600)); 
    gigaDate.setMinutes(gigaDate.getMinutes() + Math.floor((((gigaSecond % 31536000) % 86400) % 3600)/60)); 
    gigaDate.setSeconds(gigaDate.getSeconds() + (((gigaSecond % 31536000) % 86400) % 3600) % 60); 

    console.log("this should equal the first console log: " + this.userDate); 
    console.log("this should equal the new date gigaDate: " + gigaDate); 
} 

這就是現在輸出以下對我來說:

This is the first console log: Mon Aug 01 2016 11:43:57 GMT+1000 (AUS Eastern Standard Time)

this should equal the first console log: Mon Aug 01 2016 11:43:57 GMT+1000 (AUS Eastern Standard Time)

this should equal the new date gigaDate: Thu Apr 16 2048 13:30:37 GMT+1000 (AUS Eastern Standard Time)

+0

這個作品!非常感謝。 – user5854440

相關問題