Reputation: 3948
I instanced a new object
with new
keyword.DigitalClock
and AnalogClock
inheritance from base Clock
class. After that I console.log
tick()
function from childclass
. But console display undefined
and result from tick()
. What's wrong with me?
clock.ts
class Clock {
h: number;
m: number;
constructor(h: number, m: number) {
this.h = h;
this.m = m;
}
}
export class DigitalClock extends Clock {
constructor(h: number, m: number) {
super(h, m);
}
tick(): void {
console.log(`beep beep at ${this.h}: ${this.m}`);
}
}
export class AnalogClock extends Clock {
constructor(h: number, m: number) {
super(h, m);
}
tick(): void {
console.log(`tick tock at ${this.h}:${this.m}`);
}
}
app.ts
import { DigitalClock, AnalogClock } from "./clock";
const digital = new DigitalClock(1, 23);
const analog = new AnalogClock(2, 31);
console.log(digital.tick());
console.log(analog.tick());
result from console
beep beep at 1: 23
undefined
tick tock at 2:31
undefined
Upvotes: 0
Views: 37
Reputation: 26005
This:
console.log(digital.tick());
First runs digital.tick
, which calls
console.log(`beep beep at ${this.h}: ${this.m}`)
which already outputs to the console - that beep beep you wanted. But then the function returns to your original line, which attempts to send to the console the return value from digital.tick
. As there is no such value, you get the undefined
output. Just call the functions, no need to console.log
them as well, since you already do that in the function:
digital.tick();
analog.tick();
Upvotes: 3