2014-04-11 44 views
0

我在這裏看到類似的問題,但沒有解決方案解決了我的問題。我試圖延長PixiJS的BitmapText類來創建一個通用的文本對象:JavaScript:Object [object global]沒有方法

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

不管是什麼,我得到的即使該函數在PIXI.BitmapText中也是錯誤Object [object global] has no method updateText。更何況整個timeFunc的事情似乎是多餘的,但在此之前,我得到了錯誤Object [object global] has no method updateTime

爲什麼我會收到此錯誤?

+0

參見[如何訪問一個回調中正確的'this' /背景?](http://stackoverflow.com/questions/20279484/如何訪問這個正確的回調內部) –

+0

這非常有幫助菲利克斯,謝謝! –

回答

2

這行看起來可疑:

this.timeFunc = this.updateTime(); 

timeFuncundefined,因爲你在呼喚updateTime,它不返回任何東西。從計時器調用的函數也有window,而不是綁定到this的對象。如果您想保留對象REFFERENCE,你需要使用bind

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

是的,這也是工作;它完成與包裝函數相同的目標(好吧'.bind()'爲你創建包裝器)。 – Pointy

+0

我做了'window.setInterval(this.updateTime.bind(this),1000);'因爲'timeFunc'反正有點破解。謝謝! –

0

當你的函數在時間間隔上被調用時,this的值不會是你的對象的實例。你必須把它包在一個函數:

var self = this; 
window.setInterval(function() { self.updateTime(); }, 1000); 
相關問題