打字稿中的替代方法

时间:2019-10-07 10:01:11

标签: angular typescript function overriding

我有以下情况:

abstract class A implements OnInit{

    ngOnInit() {
        this.method();
    }

    private method() {
        // doing stuff
    }
}

class B extends class A implements OnInit {

    ngOnInit() {
         this.method(); // B version
    }

    method() {
        // Do different stuff from A
    }
}

我知道一个可能的解决方案是将A类中的method()公开,但是在我无法编辑的库中。 在我的B组件中,我需要执行method()的自定义版本,并防止A版本发生。

这怎么实现?

1 个答案:

答案 0 :(得分:0)

如果使用抽象类,则您的方法应该是抽象的,并且不应具有任何实现。

使用如下的抽象类(https://www.tutorialsteacher.com/typescript/abstract-class

abstract class Person {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    display(): void{
        console.log(this.name);
    }

    abstract find(string): Person;
}

class Employee extends Person { 
    empCode: number;

    constructor(name: string, code: number) { 
        super(name); // must call super()
        this.empCode = code;
    }

    find(name:string): Person { 
        // execute AJAX request to find an employee from a db
        return new Employee(name, 1);
    }
}

let emp: Person = new Employee("James", 100);
emp.display(); //James

let emp2: Person = emp.find('Steve');

或者,如果您确实想在类A中实现该方法,则可以使用以下常规类(https://www.tutorialsteacher.com/typescript/typescript-class

class Car {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    run(speed:number = 0) {
        console.log("A " + this.name + " is moving at " + speed + " mph!");
    }
}

class Mercedes extends Car {

    constructor(name: string) {
        super(name);
    }

    run(speed = 150) {
        console.log('A Mercedes started')
        super.run(speed);
    }
}

class Honda extends Car {

    constructor(name: string) {
        super(name);
    }

    run(speed = 100) {
        console.log('A Honda started')
        super.run(speed);
    }
}

let mercObj = new Mercedes("Mercedes-Benz GLA");
let hondaObj = new Honda("Honda City")

mercObj.run();  // A Mercedes started A Mercedes-Benz GLA is moving at 150 mph!
hondaObj.run(); // A Honda started A Honda City is moving at 100 mph!