Is a "wrong" to return anything else besides this
in a constructor?
Take this TypeScript Queue sample:
class Queue {
private buffer: string;
constructor(buffer: string = "") {
this.buffer = buffer;
}
push(n: string): Queue {
return new Queue(this.get() + n);
}
get(): string {
return this.buffer;
}
print() {
console.log(this.buffer);
}
}
new Queue().add("1").add("2").add("3").print(); // prints 123
Everytime push
is called, a new Queue
instance is created.
And in a child class i would like to prepend a suffix in the queue like this.
class QueuePrefix extends Queue {
constructor() {
super();
return this.push("q:");
}
}
new QueuePrefix().add("1").add("2").add("3").print(); // prints q:123
However I must return the result from the function push, instead of 'this'.
Is this an acceptable strategy?
super
is just a way to refer to the constructor of the superclass, it's used like any other method call, you can pass parameters to it. Your Queue constructor already takes a single parameter that lets you set the initial buffer value, so you can just dosuper("q:")
.