如何存储对构造函数的引用?

jds*_*816 3 typescript

示例代码演示了相关行为:

export class NodePool {
    private tail: Node;
    private nodeClass: Function;
    private cacheTail: Node;

    constructor(nodeClass: Function) {
        this.nodeClass = nodeClass;
    }

    get(): Node {
        if (this.tail) {
            var node = this.tail;
            this.tail = this.tail.previous;
            node.previous = null;
            return node;
        } else {
            return new this.nodeClass();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例的第17行(返回new ......)会导致编译器抱怨:
"Function"类型的值不可新.

将任意类的构造函数存储在变量中的正确方法是什么,以便以后可以实例化它.

Rya*_*ugh 7

您可以使用类型文字来指定可以新建的对象.这也具有增加类型安全性的优点:

export class NodePool {
    private tail: Node;
    private cacheTail: Node;

    constructor(private nodeClass: { new(): Node; }) {
    }

    get(): Node {
        if (this.tail) {
            var node = this.tail;
            this.tail = this.tail.previous;
            node.previous = null;
            return node;
        } else {
            return new this.nodeClass();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
class MyNode implements Node {
    next: MyNode;
    previous: MyNode;
}

class NotANode {
    count: number;  
}

var p1 = new NodePool(MyNode);   // OK
var p2 = new NodePool(NotANode); // Not OK
Run Code Online (Sandbox Code Playgroud)