Overriding methods from JavaScript function classes in TypeScript

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(); // prints: JSClass.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.

0
source share
1 answer

Your problem is that you add the start method to JSClass as a member of the class instead of the class method.
To make this a method, you need to add it to the prototype:

 var JSClass = function () {} JSClass.prototype.start = function () { console.log('JSClass.start()'); } 

Then this:

 let o2 = new TSClass(); o2.start(); o2.otherStart(); 

Results in:

 JSClass.start() TSClass.start() JSClass.start() TSClass.start() TSClass.otherStart() 
+3
source

Source: https://habr.com/ru/post/1012107/


All Articles