引用内部函数中的自己的构造函数 [英] Referencing own constructor in inner function
问题描述
这是一个从一个复杂类中提取的玩具示例:
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);
}
}
}
调用静态函数后:
MyClass.makeObjectAsync(function(object:Myclass):void {...})
在第10行发生以下运行时异常:
TypeError:Error#1007:试图对非构造函数进行实例化。
为什么是这个,我能做些什么呢?
编辑
似乎 new(MyClass)()
现在我可能更困惑。
不太清楚为什么要诚实。它与匿名函数继承的范围有关,取决于它们的声明方式。
我有两个解决方案。
如果您的makeObject方法不是静态的,函数的另一种方式:
public static function makeObjectAsync(callback:Function):void {
var inner:Function = function():void {
var object:MyClass = new MyClass();
callback(object);
};
inner();
}
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.
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.
If your makeObject method was not static, it would work.
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(); }
这篇关于引用内部函数中的自己的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!