JavaScript继承中如何调用超类方法使其如同定义在派生类中?
解决原型链中getter值的链式收集问题
你当前的代码中,getCodeChain仅在基类Control中定义,子类未重写该方法。当AnotherControl实例调用getCodeChain时,this始终指向实例本身,因此this.code会直接调用AnotherControl的getter返回1;而super.getCodeChain是相对于Control的,Control的原型是Object,不存在getCodeChain方法,所以递归终止,最终只返回[1]。
不需要在所有子类中实现getCodeChain,只需修改基类的该方法,通过遍历实例的原型链,依次获取每个类上code getter的返回值即可:
class Control { get code() { return 3; } getCodeChain() { const codeChain = []; let currentProto = Object.getPrototypeOf(this); while (currentProto) { // 获取当前原型上code属性的描述符 const codeDescriptor = Object.getOwnPropertyDescriptor(currentProto, 'code'); if (codeDescriptor && typeof codeDescriptor.get === 'function') { // 调用getter并绑定当前实例上下文,确保getter内的this正确指向 codeChain.push(codeDescriptor.get.call(this)); } // 向上遍历原型链 currentProto = Object.getPrototypeOf(currentProto); } return codeChain; } } class SubControl extends Control { get code() { return 2; } } class AnotherControl extends SubControl { get code() { return 1; } } console.log((new AnotherControl()).getCodeChain()); // 输出 [1, 2, 3]
代码逻辑说明:
- 通过
Object.getPrototypeOf(this)获取实例的原型,开启原型链遍历 - 每次遍历中,用
Object.getOwnPropertyDescriptor检查当前原型是否定义了code的getter - 若存在合法的getter,调用它并将返回值加入结果数组
- 持续向上遍历原型链,直到抵达链的顶端(
null)
内容的提问来源于stack exchange,提问作者Wolfgang Amadeus
相关产品推荐
相关产品推荐

