在AngularJS Typescript中从父类创建子实例

如何从父方法为子类创建实例?

例如:

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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...