摘要:本文旨在解决 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:
子类 RosterSchedulerTableUtil:
注意事项
总结
通过将方法定义为类的实例方法,可以避免 "TypeError: (intermediate value).updateUI is not a function" 错误,并确保子类可以正确调用父类的方法。 这种方式符合 JavaScript 类继承的最佳实践,能够更好地组织和管理代码。在实际开发中,应该遵循这些原则,编写清晰、可维护的继承关系代码。
以上就是解决 JavaScript 继承中父类方法无法访问的错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号