1

我的一个类的方法动态定义了事件处理函数,但我不知道如何从这样的函数访问类的实例。这是一个例子:

public dynamic class SomeClass
{
    public function SomeClass():void
    {
    }

    public function someMethod1():void
    {
    }

    public function someMethod2(eventType:String):void
    {
        var funcName:String = "func" + eventType;
        if (this[funcName] == null)
        {
            this[funcName] = function(event:*):void
                {
                    // this.someMethod1() is not working
                    // "TypeError: Error #1006: someMethod1 is not a function.                       
                };
        }
        this[funcName]("SOME_EVENT_TYPE");
    }
}

// ...

var instance:SomeClass = new SomeClass();
instance.someMethod2();
4

1 回答 1

2

编辑1:

当我阅读您的评论时,有一种更优雅的方式,因为我受到您使用thisi keep 它的影响,但使用this不是强制性的,在您的情况下,只需删除this关键字并直接调用您的方法即可

public dynamic class SomeClass
{
    public function someMethod1():void
    {
    }

    public function someMethod2(eventType:String):void
    {
        var funcName:String = "func" + eventType;
        if (this[funcName] == null)
        {
            this[funcName] = function(event:*):void
                {
                    // just call someMethod1() it will be bound to your instance
                    someMethod1(); // here use it as you wish
                    // this.someMethod1() is not working
                    // "TypeError: Error #1006: someMethod1 is not a function.                       
                };
        }
        this.someEventDispatcher.addEventListener(eventType, this[funcName]);
    }
}

从我看到的情况来看,您将事件侦听器附加到,someEventDispatcher因此当您的事件触发时,this您的事件处理程序将引用someEventDispatcher而不是实例SomeClass

您可以将实例的引用保存到变量中,以便您可以在事件处理程序中使用它:

public dynamic class SomeClass
{
    public function someMethod1():void
    {
    }

    public function someMethod2(eventType:String):void
    {
        var funcName:String = "func" + eventType;
        if (this[funcName] == null)
        {
            var self:SomeClass=this; // here keep the ref to your instance
            this[funcName] = function(event:*):void
                {
                    self.someMethod1(); // here use it as you wish
                    // this.someMethod1() is not working
                    // "TypeError: Error #1006: someMethod1 is not a function.                       
                };
        }
        this.someEventDispatcher.addEventListener(eventType, this[funcName]);
    }
}
于 2013-06-02T13:49:48.640 回答