I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class:
var JSClass = function() {
this.start = function() {
console.log('JSClass.start()');
}
}
When I call the start()
method, it prints as expected:
let o1 = new JSClass();
o1.start();
// prints: JSClass.start()
However, when I attempt to extend this object with a TypeScript class like so:
class TSClass extends JSClass {
start() {
super.start();
console.log('TSClass.start()');
}
otherStart() {
this.start();
console.log('TSClass.otherStart()');
}
}
... the TSClass::start()
is never called. Only the start()
method defined in the JSClass
.
let o2 = new TSClass();
o2.start();
o2.otherStart();
This results in:
JSClass.start()
JSClass.start()
TSClass.otherStart()
The desired output would be:
// by calling: o2.start();
JSClass.start()
TSClass.start()
// by calling: o2.otherStart();
JSClass.start()
TSClass.start()
TSClass.otherStart()
Is this behavior intentional? If so, what is the workaround for extending ES5 object methods with TypeScript?
Check out the live demo here: https://jsfiddle.net/martinsikora/2sunkmq7/
Edit: I found a solution that worked for me.
class TSClass extends JSClass {
constructor() {
var oldStart = this.start;
this.start = () => {
oldStart.call(this);
console.log('TSClass.start()');
}
}
// ...
}
Now the functionality works as expected.