Erez
Erez

Reputation: 1953

Setting object by value instead of reference

I'm trying to init a var in JS with date from another JS object but whatever i am trying getting reference to the old object (pointer) and I need it not to change.

var lastActionDate = new Date(mainLastActionDate);
var nowDate = new Date();
var tmpLastActionDate = lastActionDate;

if ((tmpLastActionDate.setDate(tmpLastActionDate.getDate() + 7)) > nowDate)

The last line is the problematic line. I thought that lastActionDate should not be changed and i need it to stay with the old date, but it changes with tmpLastActionDate and i am guessing because it is a pointer.

How can one set a date object by value instead of reference?

Upvotes: 0

Views: 151

Answers (2)

nicopico
nicopico

Reputation: 3636

You have to clone your original Date object. You can use this method :

var date = new Date();
var copiedDate = new Date(date.getTime());

Reference: How to clone a Date object in JavaScript

Upvotes: 1

mpm
mpm

Reputation: 20155

Try this :

d=new Date()
e=new Date(d.valueOf())

Upvotes: 2

Related Questions