【发布时间】:2015-08-23 13:23:54
【问题描述】:
add 方法没有按预期工作。当我有 2 个时间对象 t(全 0)和 t2(1 分钟)时。当我将 t2 添加到 t 时,t 不会改变,但是当我在 t 上调用我的 toString 方法时,它给了我预期的值。如果这没有意义,这就是我的意思:An example of what I mean!
我认为问题在于 t 的全局引用在调用 add 后没有更新。我就是不明白为什么。
我想知道为什么它不起作用,而不仅仅是如何解决问题。
Time = function(pyear, pmonth, pdate, phour, pminute, psecond)
{
var that = this;
that.year = 0;
that.month = 0;
that.date = 0;
that.hour = 0;
that.minute = 0;
that.second= 0;
//constructor
if(pyear !== undefined)
{
that.year = pyear;
that.month = pmonth;
that.date = pdate;
that.hour = phour;
that.minute = pminute;
that.second = psecond;
}
//adds toAdd time object to time
function add(toAdd)
{
that.year += toAdd.year;
that.month += toAdd.month;
that.date += toAdd.date;
that.hour += toAdd.hour;
that.minute += toAdd.minute;
that.second += toAdd.second;
}
//returns time as a String
function toString()
{
var toReturn = "";
if(that.year < 1000)
{
if(that.year < 100)
{
if(that.year < 10)
{
toReturn += "0";
}
toReturn += "0";
}
toReturn += "0";
}
toReturn += that.year + "-";
if(that.month < 10)
{
toReturn += "0";
}
toReturn += that.month +"-";
if(that.date < 10)
{
toReturn += "0";
}
toReturn += that.date +"T";
if(that.minute < 10)
{
toReturn += "0";
}
toReturn += that.minute +":";
if(that.second < 10)
{
toReturn += "0";
}
toReturn += that.second;
//year +"-"+ month +"-"+ date +"T"+ hour +":"+ minute +":"+ second
return toReturn;
}
return{
year: that.year,
month: that.month,
date: that.date,
hour: that.hour,
minute: that.minute,
second: that.second,
add: add,
toString: toString
}
};
【问题讨论】:
-
为什么要返回一个对象?你能输出
Time()结果和new Time()吗?结果对象是什么? -
@zmii imgur.com/VNi2vbl
标签: javascript class scope closures