
摘要:本文旨在解决 JavaScript ES6 类继承中,子类调用 super 关键字时,父类方法出现 "TypeError: (intermediate value).updateUI is not a function" 错误的问题。通过分析错误原因和提供修改后的代码示例,帮助开发者理解并避免类似错误,确保继承关系的正确实现和父类方法的有效调用。
在 JavaScript 中使用 ES6 类进行继承时,有时会遇到子类无法通过 super 关键字访问父类方法的问题,抛出 "TypeError: (intermediate value).updateUI is not a function" 这样的错误。这通常是由于父类的方法定义方式不正确导致的。
问题分析
在提供的代码示例中,父类 RosterTableUtil 的 updateUI 方法是在构造函数内部定义的,并赋值给 this.updateUI。虽然这种方式在功能上可以实现,但在继承场景下,会导致子类无法正确访问和调用父类的 updateUI 方法。
立即学习“Java免费学习笔记(深入)”;
解决方案
为了解决这个问题,应该将 updateUI 方法定义为类的实例方法,而不是在构造函数内部赋值。 可以使用 ES2022 引入的私有字段来替代构造函数中的变量声明。
修改后的代码示例
以下是修改后的代码示例,展示了如何正确定义父类和子类,并确保子类可以成功调用父类的 updateUI 方法:
class RosterTableUtil {
#highLightCellIndex = -1;
#highLightRowIndex = -1;
updateUI(cellIndex, rowIndex) {
this.#highLightCellIndex = cellIndex;
this.#highLightRowIndex = rowIndex;
console.log(`RosterTableUtil row ${this.#highLightRowIndex}, cell ${this.#highLightCellIndex}`);
}
}
class RosterSchedulerTableUtil extends RosterTableUtil {
updateUI(cellIndex, rowIndex) {
super.updateUI(cellIndex, rowIndex);
// do other stuff
console.log("RosterSchedulerTableUtil updateUI called"); // 示例:添加子类自己的逻辑
}
}
const util = new RosterSchedulerTableUtil();
util.updateUI(1, 2); // 输出:RosterTableUtil row 2, cell 1 \n RosterSchedulerTableUtil updateUI called
util.updateUI(3, 4); // 输出:RosterTableUtil row 4, cell 3 \n RosterSchedulerTableUtil updateUI called代码解释
-
父类 RosterTableUtil:
- #highLightCellIndex 和 #highLightRowIndex 被声明为私有字段,使用 # 前缀表示,只能在类内部访问。
- updateUI 方法直接定义在类中,成为实例方法。
-
子类 RosterSchedulerTableUtil:
- 通过 extends RosterTableUtil 继承父类。
- updateUI 方法重写了父类的方法,并使用 super.updateUI(cellIndex, rowIndex) 调用了父类的实现。
注意事项
- 确保父类的方法定义在类中,而不是在构造函数内部赋值。
- 使用 super 关键字时,要确保父类已经定义了相应的方法。
- 理解 JavaScript 中 this 的指向,特别是在继承关系中。this 始终指向调用该方法的对象。
- 合理利用 ES6 的类和继承特性,提高代码的可读性和可维护性。
总结
通过将方法定义为类的实例方法,可以避免 "TypeError: (intermediate value).updateUI is not a function" 错误,并确保子类可以正确调用父类的方法。 这种方式符合 JavaScript 类继承的最佳实践,能够更好地组织和管理代码。在实际开发中,应该遵循这些原则,编写清晰、可维护的继承关系代码。










