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

♀尐吖头ヾ 提交于 2020-01-14 07:51:12

问题


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:


+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();
    }
}



回答2:


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 i.e. 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();
}



回答3:


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.




回答4:


you need to generate a constructor and declare your variable in the class, not the function:

package com.domain { 
    public class SomeClass { 
        private static var helper:Helper 
        public function SomeClass() {
           helper = new Helper(); 
        }
    } 
} 

class Helper { 
} 


来源:https://stackoverflow.com/questions/11010041/as3-typeerror-error-1007-instantiation-attempted-on-a-non-constructor

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