javascript - Why do these objects all have the same date? -
i don't seem understand why foo.dates same value. expecting increase 1 day each iteration.
if explain why , possible solution nice :)
thank you.
date.prototype.nextday=function() { this.setdate(this.getdate()+1); return this; } adate = new date(0); function foo() { this.date = adate.nextday(); } ary = new array(); (i=1;i<5;i++){ ary.push(new foo()); } console.log(json.stringify(ary, null, 4));
foo objects:
[ { "date": "1970-01-05t00:00:00.000z" }, { "date": "1970-01-05t00:00:00.000z" }, { "date": "1970-01-05t00:00:00.000z" }, { "date": "1970-01-05t00:00:00.000z" } ]
because adate referred in foo function, , this.date = adate.nextday()
doesn't clone it. creates new reference same object.
so using same instance of date (adate) foo instances.
you don't need change prototype of date or use new, if want increment since jan 1 1970 function work :-
var nextdate = (function() { var days = 0; return function() { var date = new date(0); date.setdate(date.getdate() + ++days); return date; } })();
nextdate(); //fri jan 02 1970 01:00:00 gmt+0100 (w. europe standard time)
nextdate(); //sat jan 03 1970 01:00:00 gmt+0100 (w. europe standard time)
if want first call nextdate give jan 1 change ++days days++
Comments
Post a Comment