如何为返回新类对象的函数指定类型
我正在使用谷歌闭包编译器来检查我的 javascript 代码。我有一个函数,它创建然后返回一个新的“类”。也就是说,一个函数返回一个可以应用 new 的对象,并返回该类的“实例”对象。例如,
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
的构造函数。
任何和所有的帮助将不胜感激。
I am using google closure compiler to typecheck my javascript code. I have a function which creates and then returns a new "class." That is, a function which returns an object which can have new applied to it and returns an "instance" object of that class. E.g.,
var newclass = createFactory('Car');
var acar = new newclass();
acar.show(); // executes newclass.prototype.show()
newclass.staticmethod(); // executes newclass.staticmethod()
The show and staticmethods were created by the createFactory
method.
I am having trouble defining the type of newclass to the google closure compiler so that it recognizes newclass as a constructor which has a class method staticmethod
and an instance method show
.
Any and all help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设生成的工厂有一些公共基类或接口(我将使用 KnownType)。这应该可以解决问题:
这表示“newClass”是一个使用“new”调用的函数,它返回一个 KnownType 的实例,在这种情况下,它被声明为不带任何参数,但你可以。
CreateFactory
可以将此类型声明为其返回类型,或者您通常使用类型的任何地方。Assuming the generated factory has some common base class or interface (I'll use KnownType). This should do the trick:
This says that "newClass" is a function to be called using "new" that returns a instance of KnownType, in this case it is declared as not taking any parameters, but you can.
CreateFactory
can declare this type as its return type, or anywhere you would normally use a type.