gpt4 book ai didi

javascript - 为什么对私有(private)变量的引用没有被更新?

转载 作者:行者123 更新时间:2023-12-03 09:56:38 25 4
gpt4 key购买 nike

add 方法没有按预期工作。当我有 2 个时间对象 t (全 0)和 t2 (1 分钟)时。当我将 t2 添加到 t 时,t 不会改变,但是当我在 t 上调用 toString 方法时,它给出了预期值。如果这没有意义的话,我的意思是:An example of what I mean !

我认为问题是在调用 add 之后,t 的全局引用没有更新。我就是不明白为什么。

我想知道为什么它不起作用,而不仅仅是如何解决问题。

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 函数返回时,您将返回一个新对象,其中包含年、月、日期等的复制值。

return{ // Create a new Object
year: that.year, // copy the value from that.year to year
month: that.month,
date: that.date,
hour: that.hour,
minute: that.minute,
second: that.second,
add: add,
toString: toString
}

与 return 语句相反,您应该将函数 addtoString 分配给 this 引用。

 // return{
// year: that.year,
// month: that.month,
// date: that.date,
// hour: that.hour,
// minute: that.minute,
// second: that.second,
// add: add,
// toString: toString
//}
this.toString = toString;
this.add = add;
}

您不需要从构造函数返回值。请参阅https://jsfiddle.net/dwat001/xf1Lfvv5/

关于javascript - 为什么对私有(private)变量的引用没有被更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30719966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com