Referencing own constructor in inner function

2019-07-28 18:19发布

问题:

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.