我正在尝试学习如何创建createjs对象。
我正在调查createjs / tutorials / Inheritance / 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的功能是什么吗? 那是一个无限循环吗?
答案 0 :(得分:2)
这不是一个无限循环,正在发生的是你正在制作旧初始化的'副本'(实际上只是一个新的参考)。
p.Container_initialize = p.initialize;
此处p.initialize
与createjs.Container.prototype.initialize
相同。
当你写:
Button.prototype.initialize = function(...) {
您正在覆盖Container.prototype.initialize
,但自从您将其保存在Container_initialize
后,您仍可以将其保留。
至于函数的作用,这是读取源代码的问题,它可能设置容器对象需要的任何内部东西。这就是为什么你不能不称呼它。