Переопределить методы в Typescript - PullRequest
1 голос
/ 07 октября 2019

У меня следующая ситуация:

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 общедоступным, но его в библиотеке я не могу редактировать. В моем компоненте B мне нужно сделать собственную версию метода () и предотвратить возникновение версии A.

Как этого достичь?

1 Ответ

0 голосов
/ 07 октября 2019

Если вы используете абстрактный класс, ваш метод должен быть абстрактным и не должен иметь никакой реализации.

Используйте абстрактный класс следующим образом (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!
...