Javascript 如何为返回新类对象的函数指定类型
我正在使用google闭包编译器对我的javascript代码进行类型检查。我有一个函数,它创建一个新的“类”,然后返回一个新的“类”。也就是说,一个函数返回一个对象,该对象可以应用新的对象,并返回该类的一个“实例”对象。例如:Javascript 如何为返回新类对象的函数指定类型,javascript,types,google-closure-compiler,Javascript,Types,Google Closure Compiler,我正在使用google闭包编译器对我的javascript代码进行类型检查。我有一个函数,它创建一个新的“类”,然后返回一个新的“类”。也就是说,一个函数返回一个对象,该对象可以应用新的对象,并返回该类的一个“实例”对象。例如: var newclass = createFactory('Car'); var acar = new newclass(); acar.show(); // executes newclass.prototype.show() newclass.staticm
var newclass = createFactory('Car');
var acar = new newclass();
acar.show(); // executes newclass.prototype.show()
newclass.staticmethod(); // executes newclass.staticmethod()
show和staticmethods是通过createFactory
方法创建的
我在为google闭包编译器定义newclass的类型时遇到了问题,因此它无法将newclass识别为一个构造函数,该构造函数具有类方法staticmethod
和实例方法show
如果生成的工厂有一些公共基类或接口(我将使用KnownType),我们将不胜感激。这应该可以做到:
/** @type {function(new:KnownType)} */
var newClass = createFactory();
这表示“newClass”是一个使用“new”调用的函数,该函数返回KnownType的实例,在本例中,它被声明为不带任何参数,但您可以
CreateFactory
可以将此类型声明为其返回类型,或者声明为您通常使用的任何类型。是否CreateFactory()
返回函数?你能给我们看看createFactory的代码吗?createFactory在一个外部库中,但是,类似这样的东西:createFactory(名称)={var x=function(){};x.name=name;x.prototype.show=function(){…};x.staticmethod=function(){…};return x;}