user5854440 user5854440 - 4 months ago 9
Javascript Question

JavaScript: Copy an object key value without changing the referenced object key

I'm writing a prototype function that takes a date from the object and then adds a gigasecond (10 billion seconds) to it. Here is my code:

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);
}


The date entered into
this.userDate
is
Sunday, Sep 13, 2015 18:00
. I want to keep
this.userDate
intact for another part of the function. Problem is, when I change
gigaDate
, it also changes
this.userDate
. Here is the console output:

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)


Any hints?

Answer

You want to create a new date object instead of simply assigning one to another.

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 now outputs the following for me:

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)

Comments