Following my last thread (here), I think I’ve pin-pointed the problem.
However, I’m getting a headache trying to understand why this is occurring.
Context: I have an Object called “Schedule” within which I’m creating 52 “week” Objects. Each week has functions to return the start and end dates in a MySQL format, the JS date Object and a label. More details in previous post.
It works perfectly, apart from when I’m trying to initiate the “EndDate”.
/* --- LEAP.Schedule.week Object --- */
LEAP.Schedule.week = function(n_date, n_week){
this.week = n_week;
this.date = n_date;
this.year = this.date.getFullYear();
this.month = this.date.getMonth();
this.month += 1;
this.day = this.date.getDate();
alert("BEFORE " + this.date.getDate());
this.end_date = this.setEndDate(this.date);
alert("AFTER " + this.date.getDate());
};
LEAP.Schedule.week.prototype.setEndDate = function(date) {
var ret_date = date;
ret_date.setDate(ret_date.getDate() + 6);
return(ret_date);
}
Using the alerts either side of “this.setEndDate” being run, I can see that “this.date” is being incremented every time “setEndDate” is being run.
I don’t want that to happen: I want “this.date” to stay as the date being passed into the week Object, and I want a separate variable called “this.end_date” which is basically this.date plus six days.
I’m presuming this is a referencing issue. I found this article: http://www.snook.ca/archives/javascript/javascript_pass/ but truth be told I don’t understand it… 🙂
Could anyone enlighten me?
I think it’s because you’re passing “this.date” through to setEndDate each time, so when you run ret_date.setDate you are doing it to this.date. This is because “date” is an object whose reference is being passed around.
You should be able to change it as such:
The mydate object will now be modified, which won’t affect your code.
Better still, you could just tell the set end date to change the
this.end_date, based onthis.dateand you shouldn’t need to pass anything around!