次のコードの場合、
$(function() {
a = new Date("2008-1-2");
monthDiff = function(now, then) {
var months;
months = (now.getFullYear() - then.getFullYear()) * 12;
months -= then.getMonth() + 1;
months += now.getMonth();
return months;
};
intervalToDate = function(interval, start, unit) {
{
return {
day: function() {return new Date(start.getTime() + (interval*24*60*60*1000)); },
week: function() {return new Date(start.getTime() + (interval*7*24*60*60*1000)); },
month: function() {
// the result value below will not return a date object when running (only an object), what is weird is in the debug console, using the line below will totally return a date object.
var result = new Date(start.getTime() + interval*4*7*24*60*60*1000);
while (monthDiff(result, start) !== interval) {
result += 24*60*60*1000;
}
return result;
} ,
year: function() {
return start.getFullYear() + interval;
}
}[unit]();
}
};
console.log(intervalToDate(20, a, "day"));
console.log(intervalToDate(20, a, "week"));
console.log(intervalToDate(20, a, "month"));
console.log(intervalToDate(20, a, "year"));
})
この行:
month: function() {
// the result value below will not return a date object when running (only an object), what is weird is in the debug console, using the line below will totally return a date object.
var result = new Date(start.getTime() + interval*4*7*24*60*60*1000);
結果はデバッグコンソールに正しく返されます。しかし、実行すると、どういうわけかそれは日付オブジェクトではなくなったので、getFullYear関数を呼び出そうとすると「メソッドエラーなし」に遭遇しました。