Search code examples
objectjavascriptextend

JavaScript: Object [object global] has no method


I've seen similar questions here, but none of the solutions fixed my problem. I'm trying to extend PixiJS's BitmapText class to create a generic text object:

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;

And then extend that for a simple clock that updates every second:

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();
    }
};

No matter what, I get the error Object [object global] has no method updateText even though that function is in PIXI.BitmapText. Not to mention that the whole timeFunc thing seems superfluous, but before that I got the error Object [object global] has no method updateTime.

Why am I getting this error?


Solution

  • This line looks suspicious:

    this.timeFunc = this.updateTime();
    

    timeFunc will be undefined, since you are calling updateTime, and it doesn't return anything. Also a function called from a timer will have window, and not the object bound to this. If you want to retain the object refference, you need to use bind

    this.timeFunc = this.updateTime.bind(this);