我试图在cocos2d-js中扩展cc.LabelTTF类。下面的代码有问题:
var FlowingText = cc.LabelTTF.extend({
update : function(dt) {
console.log("update. dt:"+dt);
}
}); 我期望FlowingText继承cc.LabelTTF的所有属性,但是下面的代码崩溃了:
FlowingText.create("", "r-mplus-1c-m.ttf", 24);
给我一个错误
Uncaught TypeError: undefined is not a function
如果我这样做的话,代码可以正常工作:
cc.LabelTTF.create("", "r-mplus-1c-m.ttf", 24);
'create‘函数是cc.LabelTTF的一个属性,我认为我已经扩展了它,但是我得到了这个错误。知道发生什么事了吗?
发布于 2014-07-28 19:42:38
这是一个众所周知的问题。
使用extend从cc类创建自己的类时,不会继承create方法。如果您查看一下cocos2d的任何类,您会注意到create方法总是被附加到原型中,并且由于某种原因,这绕过了扩展机制。
简而言之:您必须重写ctor方法并编写您自己的create方法。
这是在coco的代码文件中使用的标准方法:
var FlowingText = cc.LabelTTF.extend({
ctor: function(text, font, size){
this._super(text, font, size);
//possibly do other stuff here if necesary
},
update : function(dt) {
console.log("update. dt:"+dt);
}
}); 你可以用这个和:
var myFT = new FlowingText("asdf", "r-mplus-1c-m.ttf", 24);或者你可以这样做:
FlowingText.create = function(text, font, size) {
return new FlowingText(text, font, size);
};像这样使用它:
var myFT = FlowingText.create("asdf", "r-mplus-1c-m.ttf", 24);额外:请注意,cc.LabelTTF.create()和new cc.LabelTTF()可能不一定相同。当您重写ctor方法时,您正在更改它用new MyClass()调用的内容。如果您试图在您的create中重写extend方法,您将得到一个错误(或者至少我上次尝试的情况是这样的)。
发布于 2014-07-28 12:19:10
就像这样:
var FlowingText = $.extend(cc.LabelTTF, {
update : function(dt) {
console.log("update. dt:"+dt);
}})现在它应该可以工作了,FlowingText.create("", "r-mplus-1c-m.ttf", 24);
演示
https://stackoverflow.com/questions/24992995
复制相似问题