【发布时间】:2016-11-03 09:50:51
【问题描述】:
我正在尝试覆盖 JavaScript (ES5) 基于函数的类中定义的对象方法:
var JSClass = function() {
this.start = function() {
console.log('JSClass.start()');
}
}
然后调用start() 方法按预期打印:
let o1 = new JSClass();
o1.start();
// prints: JSClass.start()
但是,如果我尝试使用 TypeScript 类扩展此对象,例如:
class TSClass extends JSClass {
start() {
super.start();
console.log('TSClass.start()');
}
otherStart() {
this.start();
console.log('TSClass.otherStart()');
}
}
...然后TSClass::start() 永远不会被调用。只有JSClass中定义的start()。
let o2 = new TSClass();
o2.start();
o2.otherStart();
这只是打印:
JSClass.start()
JSClass.start()
TSClass.otherStart()
我希望打印:
// by calling: o2.start();
JSClass.start()
TSClass.start()
// by calling: o2.otherStart();
JSClass.start()
TSClass.start()
TSClass.otherStart()
这是设计使然吗?那么如何使用 TypeScript 扩展 ES5 对象方法呢?
观看现场演示:https://jsfiddle.net/martinsikora/2sunkmq7/
编辑:我最终使用了这个。
class TSClass extends JSClass {
constructor() {
var oldStart = this.start;
this.start = () => {
oldStart.call(this);
console.log('TSClass.start()');
}
}
// ...
}
现在它可以按预期工作了。
【问题讨论】:
标签: javascript typescript