【发布时间】:2011-03-09 20:59:48
【问题描述】:
好吧,经过一天后,我设法将问题缩小到 2 行代码。也许我试图错误地使用这个语句。
function scheduleItemView(myId){
this.update = function(show){
document.getElementById(this.id+'-title').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-title-overlay').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-description').innerHTML = truncate(show.description,190);
document.getElementById(this.id+'-time-start').innerHTML = show.startTime;
document.getElementById(this.id+'-time-end').innerHTML = show.endTime;
};
this.id=myId;
return true;
}
function nowNextView(){
this.now = new scheduleItemView('now');
this.next = new scheduleItemView('next');
this.update = function(type,args){
var myshow=args[0];
// problem is below. I have to use the global name to access the update method.
myNowNextView.now.update(myshow.now);
myNowNextView.next.update(myshow.next);
// whereas what I want to do is reference them using the "this" command like below.
// this.now.update(myshow.now);
// this.next.update(myshow.next);
// the above doesnt work. The update method in scheduleItemView is not seen unless referenced globally
// BUT even more infuriating, this.now.id does return "now" so it can access the object, just not the method
// any ideas?
};
}
然后用
实例化对象var myNowNextView = new nowNextView();
然后我运行方法:
myNowNextView.update(stuff);
我试图在程序主体中描述问题。代码中没有抛出任何错误,我不得不在它勉强告诉我它找不到方法之前做一个 try/catch。 设计是否存在某种缺陷?我不能这样做吗? 提前谢谢了, 史蒂夫
【问题讨论】:
-
实际上它看起来应该可以工作。如果你调用
myNowNextView.update(),那么this里面的update将引用myNowNextView。
标签: javascript this javascript-objects