子类调用父类updateUI方法报错:Uncaught TypeError问题咨询
问题
父类代码:
export default class RosterTableUtil{ constructor() { let highLightCellIndex = -1, highLightRowIndex = -1; // 省略其他逻辑 this.updateUI = (cellIndex, rowIndex) => { highLightCellIndex = cellIndex; highLightRowIndex = rowIndex; } } }
子类代码:
import RosterTableUtil from "./RosterTableUtil"; export default class RosterSchedulerTableUtil extends RosterTableUtil{ constructor(){ super(); // 省略其他逻辑 this.updateUI = (cellIndex, rowIndex) => { super.updateUI(cellIndex, rowIndex); updateSelectRegion(cellIndex, rowIndex); } } }
调用子类RosterSchedulerTableUtil的updateUI方法时,触发报错:
Uncaught TypeError: (intermediate value).updateUI is not a function
修复方案
原因分析
父类的updateUI是在构造函数中直接挂载到实例this上的属性,不属于类的原型方法。而super.updateUI是去父类的原型链上查找方法,自然找不到,因此报错。
方案一:将父类方法改为原型方法(推荐)
把父类的updateUI定义为类的原型方法,同时将原来的局部变量改为实例属性,确保方法能访问到:
修改后的父类代码:
export default class RosterTableUtil{ constructor() { // 把局部变量改为实例属性 this.highLightCellIndex = -1; this.highLightRowIndex = -1; // 省略其他逻辑 } // 定义为原型方法 updateUI(cellIndex, rowIndex) { this.highLightCellIndex = cellIndex; this.highLightRowIndex = rowIndex; } }
子类无需额外修改,super.updateUI就能正常调用父类的原型方法,符合类的继承设计规范,便于后续维护和扩展。
方案二:保存父类实例方法后再重写(临时兼容)
如果无法修改父类代码,可以在子类构造函数中,先保存父类实例的updateUI方法,再重写自己的版本:
修改后的子类代码:
import RosterTableUtil from "./RosterTableUtil"; export default class RosterSchedulerTableUtil extends RosterTableUtil{ constructor(){ super(); // 先保存父类实例的updateUI方法 const parentUpdateUI = this.updateUI; // 省略其他逻辑 this.updateUI = (cellIndex, rowIndex) => { parentUpdateUI(cellIndex, rowIndex); // 调用父类方法 updateSelectRegion(cellIndex, rowIndex); } } }
这种方式属于临时兼容方案,仅适用于无法修改父类的场景,长期来看原型方法的方案更优。
内容的提问来源于stack exchange,提问作者The KNVB
相关产品推荐
相关产品推荐

