AS3 TypeError: Error #1007: Instantiation attempted on a non
For some reason I can't get this to work (heavily simplified code that fails):
package com.domain {
public class SomeClass {
private static var helper:Helper = new Helper();
}
}
class Helper {
}
It compiles, but throws upon first access of SomeClass
:
TypeError: Error #1007: Instantiation attempted on a non-constructor.
at com.domain::SomeClass$cinit()
...
+1 to Darren. Another option is to move the Helper
class to the top of the file
class Helper {
}
package com.domain {
public class SomeClass {
private static var helper:Helper = new Helper();
}
}
The non-constructor error is the compiler's awkward way of saying 'you have called a constructor for a class I have not seen yet'; if it were a bit smarter, it could check the file (compilation unit) for internal classes before complaining... mehhh
Seeing as you have given your static variable private
access, obviously you intend to only use the instance internally to SomeClass
(assumption; could be passed out as a return value).
The following solution defers creation of the static var to when the internal class is initialized ie when the (presumably implicit) Helper.cinit()
is invoked, rather than SomeClass.cinit()
when Helper
does not exist yet:
package com.domain {
public class SomeClass {
public function doSomething(param:*):void {
// ... use Helper.INSTANCE
}
}
}
class Helper {
public static const INSTANCE:Helper = new Helper();
}
I think it can't work with Helper and SomeClass both in the same file. When SomeClass is initialized, the Helper class has not been initialized yet, and so a Helper object can't be created.
Moving Helper to a separate file should solve the problem.
链接地址: http://www.djcxy.com/p/60604.html