Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript:是否可以定义一个类来创建函数的实例?_Typescript - Fatal编程技术网

TypeScript:是否可以定义一个类来创建函数的实例?

TypeScript:是否可以定义一个类来创建函数的实例?,typescript,Typescript,在TypeScript中,类是否可能是函数实例的构造函数?我的设想是: class SomeThing { (name: string) { // do something with name } } let thing = new SomeThing(); thing('John Doe'); 这在技术上是可能的(这需要一些技巧,我不打算在这里写),但你真的不想这样做;原因如下 new操作符创建一个新对象(不是函数),其\uuuuu proto\uuuu是操作

在TypeScript中,类是否可能是函数实例的构造函数?我的设想是:

class SomeThing {
    (name: string) {
       // do something with name
    }
}

let thing = new SomeThing();
thing('John Doe');
这在技术上是可能的(这需要一些技巧,我不打算在这里写),但你真的不想这样做;原因如下

new
操作符创建一个新对象(不是函数),其
\uuuuu proto\uuuu
是操作数的
原型。这意味着您不可能让
new
操作符返回可调用的东西,除非您显式地从构造函数中返回其他东西


但是,如果您从构造函数中返回其他内容,那么
thing instanceof something
将是
false
,并且您将无法使用
thing
中类的
原型
方法。因此,在这一点上,它的行为根本不像一个
类,而你最好只是拥有一个工厂函数,它可以做任何它想做的事情。

并补充@Ryan的优秀答案:你不需要一个“类”来实现你想做的事情。您只需创建一个返回另一个
函数的
函数
。如果需要,可以使用(外部功能)“存储”其他配置。