I am trying to override the object method defined in the JavaScript function class (ES5):
var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } }
Then, calling the start()
method prints as expected:
let o1 = new JSClass(); o1.start();
However, if I try to extend this object with the TypeScript class, for example:
class TSClass extends JSClass { start() { super.start(); console.log('TSClass.start()'); } otherStart() { this.start(); console.log('TSClass.otherStart()'); } }
... then TSClass::start()
never called. Only start()
defined in JSClass
.
let o2 = new TSClass(); o2.start(); o2.otherStart();
This is true:
JSClass.start() JSClass.start() TSClass.otherStart()
I look forward to printing:
// by calling: o2.start(); JSClass.start() TSClass.start() // by calling: o2.otherStart(); JSClass.start() TSClass.start() TSClass.otherStart()
Is it for design? Then, how can I extend the methods of an ES5 object using TypeScript?
See demo version: https://jsfiddle.net/martinsikora/2sunkmq7/
Edit: I ended up using this.
class TSClass extends JSClass { constructor() { var oldStart = this.start; this.start = () => { oldStart.call(this); console.log('TSClass.start()'); } }
Now it works as expected.