【问题标题】:How do I store a reference to a constructor?如何存储对构造函数的引用?
【发布时间】:2012-11-15 16:21:51
【问题描述】:

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

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

示例的第 17 行(return new......)导致编译器抱怨:
'Function' 类型的值不是新的。

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 2020-04-30
      • 2020-03-04
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多