开发者

Prototype methods not working on textField

This doesn't make any sense to my feeble brain, and I've reached my googlefu limit.

I have a bunch of prototype methods that I use to speed development up, and most of them are attached to DisplayObject or InterActiveObject. Here's an example of one such prototype:

DisplayObject.prototype.$click = function(clicked:Function, released:Function = null):void{
    this.addEventListener(MouseEvent.MOUSE_DOWN, function():void {
            clicked();
        });

    if(released != null){
        this.addEventListener(MouseEvent.MOUSE_UP, function():void {
            released();
        });
    }
}

If I call any movieClipInstance.$click(someFunction), it binds correctly. However, if I attempt to do that on a TextField instance, it gives me the following compile-time error. Call to a possibly undefined method $click through a reference with static type flash.text:TextField.

According to 开发者_StackOverflow社区the reference, TextField inherits DisplayObject, but just to be sure I redefined my prototype explicitly for TextFields. Still the same error. :(


You can always extend TextField and add the methods there. In fact, you should consider doing this for all the other objects as well: Extend MovieClip, Sprite, or whatever other DisplayObject you want to add the $click method to. Then let all your other objects inherit ClickMovie, ClickSprite etc. instead of the generic classes. It should not be a lot more code to write, but your application will be considerably faster and type safe.

You should use prototype only in cases where you have to add or override methods or properties dynamically at runtime.

An in-depth explanation on how inheritance works in AS3 can be found here.


Apparently, prototype methods can only be assigned to classes declared with the dynamic keyword. Went to the reference to see if my experiences matched that assertion and sure enough TextField is defined as public class TextField. MoveClip on the otherhand is defined as public dynamic class MovieClip

Seems a bit wonky to me that a non dynamic class still can't access the prototype methods of its dynamic ancestors though. Inheritance strikes again!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜