Referencing own constructor in inner function

大兔子大兔子 提交于 2019-12-13 00:46:32

问题


Here's a toy example distilled from a complex class:

public class MyClass {
    public function MyClass() {
         trace('Created');
    }

    public static function makeObjectAsync(callback:Function):void {
        inner();

        function inner():void {
            var object:MyClass = new MyClass(); // line 10
            callback(object);
        }
    }
}

After calling the static function:

MyClass.makeObjectAsync(function(object:Myclass):void { ... })

the following run-time exception occurs at line 10:

TypeError: Error #1007: Instantiation attempted on a non-constructor.

Why is this, and what can I do about it?

Edit

It appears that new (MyClass)() works. Now I'm possibly more confused.


回答1:


Not too clear on the WHY to be honnest. It has to do with the scope inherited by anonymous functions, depending on how they are declared.

I have 2 solutions for you though.

  1. If your makeObject method was not static, it would work.

  2. Declare your anonymous function the other way :

    public static function makeObjectAsync(callback:Function):void {
        var inner : Function = function():void {
            var object:MyClass = new MyClass();
            callback(object);
        };
    
        inner();
    }
    



回答2:


You shouldn't call your variable "object". Why do you nested your inner function? Why don't you just:

public static function makeObjectAsync(callback:Function):void {
    callback(new MyClass());
}

Or if you really want that nested function:

public static function makeObjectAsync(callback:Function):void {
    inner();

    function inner():void {
        callback(new MyClass());
    }
}

And you can't recall the class' constructor again, use a function which is called in the constructor then call it again. With this you aren't referencing the constructor but creating a new instance of the class.



来源:https://stackoverflow.com/questions/12113004/referencing-own-constructor-in-inner-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!