我在这里看到过类似的问题,但没有一个解决方案解决了我的问题。我试图扩展PixiJS的BitmapText类来创建通用文本对象:
OS7.Text = function(string, x, y)
{
PIXI.BitmapText.call(this, string, {font:"12px Chicago"});
this.position.x = x;
this.position.y = y;
}
OS7.Text.prototype = Object.create( PIXI.BitmapText.prototype );
OS7.Text.prototype.constructor = OS7.Text;
然后将其扩展为一个每秒更新一次的简单时钟:
OS7.Time = function()
{
OS7.Text.call(this, "00:00 AM", 571, 5);
this.position.x = 571 - this.textWidth;
this.updateTime();
this.timeFunc = this.updateTime();
window.setInterval(this.timeFunc, 1000);
};
OS7.Time.prototype = Object.create(OS7.Text.prototype);
OS7.Time.prototype.constructor = OS7.Time;
OS7.Time.prototype.updateTime = function()
{
this.prevText = this.text;
this.date = new Date();
this.hour = this.date.getHours();
this.minute = this.date.getMinutes();
this.zero = "";
this.ampm = "AM";
if ( this.hour > 12 )
{
this.hour -= 12;
this.ampm = "PM";
}
if ( this.hour === 0 )
{
this.hour = 12;
}
if ( this.minute < 10 )
{
this.zero = "0";
}
this.setText( this.hour + ":" + this.zero + this.minute + " " + this.ampm );
if ( this.prevText !== this.text )
{
this.updateText();
}
};
无论如何,即使该函数在Object [object global] has no method updateText
中,我也会收到错误PIXI.BitmapText
。更不用说整个timeFunc
事情似乎是多余的,但在此之前我得到了错误Object [object global] has no method updateTime
。
为什么我收到此错误?
答案 0 :(得分:2)
这一行看起来很可疑:
this.timeFunc = this.updateTime();
timeFunc
将undefined
,因为您正在调用updateTime
,并且它不会返回任何内容。此外,从计时器调用的函数将具有window
,而不是绑定到this
的对象。如果要保留对象引用,则需要使用bind
this.timeFunc = this.updateTime.bind(this);
答案 1 :(得分:0)
在时间间隔调用函数时,this
的值不会成为对象的实例。你必须将它包装在一个函数中:
var self = this;
window.setInterval(function() { self.updateTime(); }, 1000);