2013-04-04 90 views
2

我想學習如何創建createjs對象。class_initialize()做了什麼?

我調查createjs /教程/繼承/ demo.html和Button.js

(function() { 
var Button = function(label, color) { 
    this.initialize(label, color); 
} 
var p = Button.prototype = new createjs.Container(); // inherit from Container 

p.label; 
p.background; 
p.count = 0; 

*p.Container_initialize = p.initialize;* 
Button.prototype.initialize = function (label, color) { 

    *this.Container_initialize();* 

    this.label = label; 
    if (!color) { color = "#CCC"; } 

    var text = new createjs.Text(label, "20px Arial", "#000"); 
    text.textBaseline = "top"; 
    text.textAlign = "center"; 

    var width = text.getMeasuredWidth()+30; 
    var height = text.getMeasuredHeight()+20; 

    this.background = new createjs.Shape(); 
    this.background.graphics.beginFill(color).drawRoundRect(0,0,width,height,10); 

    text.x = width/2; 
    text.y = 10; 

    this.addChild(this.background,text); 
    this.addEventListener("click", this.handleClick); 
    this.addEventListener("tick", this.handleTick); 
} 

p.handleClick = function (event) {  
    var target = event.target; 
    alert("You clicked on a button: "+target.label); 
} 

p.handleTick = function(event) {  
    p.alpha = Math.cos(p.count++*0.1)*0.4+0.6; 
} 

window.Button = Button; 
}()); 

有一個自我調用函數this.Container_initialize(); 我試圖將其註釋掉,導致代碼無法正常工作。 有人可以解釋什麼功能Container_initialize做? 這是一個無限循環嗎?

回答

2

這不是一個無限循環,所發生的是你正在做一箇舊的初始化的'複製'(真的只是一個新的參考)。

p.Container_initialize = p.initialize; 

這裏,p.initialize是一樣的createjs.Container.prototype.initialize。 當你寫:

Button.prototype.initialize = function(...) { 

要覆蓋Container.prototype.initialize,但因爲你在Container_initialize保存它仍然可以調用它。

至於函數做什麼,這是閱讀源代碼的問題,它可能設置容器對象需要的任何內部東西。這就是爲什麼你不能稱之爲。