2016-08-01 5 views
2

オブジェクトから日付を取得し、ギガ秒(100億秒)を追加するプロトタイプ関数を作成しています。ここに私のコードは次のとおりです。this.userDateに入力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); 
} 

日付がSunday, 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

関連する問題