2011-09-15 74 views
1

继我的最后一个线程(here),我想我已经指出了这个问题。OOP JS:变量传递/参考查询

但是,我很头疼,想知道为什么会发生这种情况。

上下文:我有一个名为“Schedule”的对象,我在其中创建52个“周”对象。每周都有函数以MySQL格式返回开始和结束日期,JS日期对象和标签。更多细节在上一篇文章中。

除了当我尝试启动“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); 

} 

使用警报任“this.setEndDate”正在运行的一面,我可以看到“this.date”正在每递增“setEndDate”正在运行的时间。我不希望发生这种情况:我希望“this.date”保留为传入星期Object的日期,并且我想要一个名为“this.end_date”的单独变量,它基本上是this.date加上六天。

我假设这是一个引用问题。我发现这篇文章:http://www.snook.ca/archives/javascript/javascript_pass/但真相被告知我不明白它... :)

任何人都可以启发我吗?

回答

2

我想这是因为你传递“this.date”通过对setEndDate每一次,所以当你运行ret_date.setDate你正在做它this.date。这是因为“日期”是一个参考被传递的对象。

你应该能够改变它是这样:

var mydate = new Date(this.date); 
this.end_date = setEndDate(mydate); 

的指明MyDate对象将被修改,这会不会影响你的代码。

更好的是,你可以告诉设定的结束日期,根据this.date改变this.end_date,你不需要传递任何东西!

+0

啊,课程!我知道我是在正确的路线上,我只是无法把头转向它。真的非常感谢你! – dunc

2

是的;

var ret_date = date; 

ret_date当你将它传递给函数作为参考,date,它本身就是this.date,其通过引用传递。

你想拷贝日期,增量& return;

LEAP.Schedule.week.prototype.setEndDate = function(date) { 
    var ret_date = new Date(date.getTime()); 
    return ret_date.setDate(ret_date.getDate() + 6); 
} 
+0

非常感谢:) – dunc

+0

他们都是参考文献 – newacct