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

前端之家收集整理的这篇文章主要介绍了在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;
    }
}

猜你在找的Angularjs相关文章