export class Entity {
add(component: Component, componentClass?: { new (): Component;}): Entity {
if (!componentClass) {
componentClass = component.constructor
}
/** sniiiiip **/
}
}
Run Code Online (Sandbox Code Playgroud)
示例的第4行(分配component.constructor)导致编译器抱怨:
属性'构造函数'不存在于'Component'类型的值上
获取对象构造函数的引用的正确方法是什么?我的理解是,JavaScript中的所有对象都有一个.constructor属性,该属性指向用于创建该对象的构造函数...
class MockFamily implements IFamily {
static instances: MockFamily[] = [];
constructor (nodeClass: { new (): Node; }, engine: Engine) {
MockFamily.instances.push(this);
}
/* sniiiiiip */
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中是否有任何方法可以instances在不使用实际类名的情况下从构造函数中访问静态值?
示例代码演示了相关行为:
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"类型的值不可新.
将任意类的构造函数存储在变量中的正确方法是什么,以便以后可以实例化它.
class MySystem extends ListIteratingSystem {
constructor (private creator: EntityCreator) {
super(MyNode, this.updateNode);
}
updateNode() {/* sniiiiip */}
/* sniiiip */
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我需要一些方法将updateNode函数传递给超级调用.编译器抱怨这说明:
Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls
关于如何解决这个问题的任何想法?这里的用例是我抽取了很多与列表遍历相关的锅炉板代码,并将其抽象到这个基类中,该基类由几个完成实际工作的特定系统扩展.基类需要调用更新,添加和删除的方法......
typescript ×4