Create a child instance from the parent class in AngularJS + Typescript

How to create an instance for a child class from the parent method?

For instance:

class Vehicle {
    public getNewInstance(): ICar {
        // What should be here? 
        return new XXXXXXXX; 
    }
}

class Car extends Vehicle {
    public getWheels(): Number {
        return 4;
    }
}

Now I need to do this to get a new Car instance:

Car.getNewInstance();

The vehicle has many advanced classes, and I prevent every child from repeating the code. In addition, children classes also have more children.

+4
source share
2 answers

Your code will not do this because you want the static method not to be an instance method.

You can do it:

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

Since it Vehiclenow has a static method getNewInstance, then all extending classes also have.
So:

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

Edit

, 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;
    }
}
+1

getNewInstance Car . -

class Car extends Vehicle {
    public getNewInstance(): Car {
        return new Car(); 
    }
}

. , .

, , factory, , . factory . , , . Vehicle factory ,

0

All Articles