在AngularJS Typescript中从父类创建子实例
发布时间:2020-12-17 16:55:36 所属栏目:安全 来源:网络整理
导读:如何从父方法为子类创建实例? 例如: class Vehicle { public getNewInstance(): ICar { // What should be here? return new XXXXXXXX; }}class Car extends Vehicle { public getWheels(): Number { return 4; }} 现在,我需要这样做以获得一个新的Car实例
如何从父方法为子类创建实例?
例如: class Vehicle { public getNewInstance(): ICar { // What should be here? return new XXXXXXXX; } } class Car extends Vehicle { public getWheels(): Number { return 4; } } 现在,我需要这样做以获得一个新的Car实例: Car.getNewInstance(); 车辆有许多扩展类,我防止在每个孩子中重复代码.此外,儿童班也有更多的孩子. 解决方法
您的代码不会这样做,因为您需要静态方法而不是实例方法.
你可以这样做: class Vehicle { public static getNewInstance(): Vehicle { return new this(); } public getWheels(): Number { throw new Error("unknown number of wheels for abstract Vehicle"); } } class Car extends Vehicle { public getWheels(): Number { return 4; } } 因为Vehicle现在有一个静态getNewInstance方法,所以所有扩展类也都有. let v = Vehicle.getNewInstance(); console.log(v); // Vehicle {} console.log(v.getWheels()); // Uncaught Error: unknown number of wheels for abstract Vehicle let c = Car.getNewInstance(); console.log(c); // Car {} console.log(c.getWheels()); // 4 编辑 如果我误解了你并且你确实想在现有实例上调用getNewInstance,那么你可以这样做: abstract class Vehicle { public abstract getNewInstance(): Vehicle; } class Car extends Vehicle { public getNewInstance(): Vehicle { return new Car(); } public getWheels(): Number { return 4; } } 或这个: class Vehicle { private ctor: { new (): Vehicle }; constructor(ctor: { new (): Vehicle }) { this.ctor = ctor; } public getNewInstance(): Vehicle { return new this.ctor(); } } class Car extends Vehicle { constructor() { super(Car); } public getWheels(): Number { return 4; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- WebService一篇非常好的入门
- [Angular] Extract Implementation Details of n
- angularjs – Angular.js和Require.Js
- angularjs – Angular-ui D3:如何实现上下文菜单
- PXE启动芯片出错代码表初始化/引导/载入Bootstra
- angularjs – 如何在$compile之后删除由angular指
- bash – Unix:计算第一列中类似条目的出现次数,
- 我应该在AngularJS中测试什么?
- 在vim中检测文件类型而没有有效的文件扩展名
- 我可以通过__meteor_bootstrap__.app挂载另一个路
热点阅读