You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS原型继承场景下如何获取对象整个继承链上所有祖先的方法?

JS实现获取对象完整继承链所有方法的方案

你当前的代码只读取了实例第一层原型的属性,仅能获取D类的方法,没有向上遍历整个继承链,因此无法拿到祖先类的方法。可以通过循环遍历原型链的方式实现需求,具体实现如下:

核心实现代码

function getAllInheritedMethods(instance) {
  // 用Set存储避免重名方法重复统计
  const methodSet = new Set();
  let currentPrototype = Object.getPrototypeOf(instance);

  // 遍历到原型链顶端(null)为止
  while (currentPrototype !== null) {
    // 拿到当前原型的所有自有属性
    const ownProperties = Object.getOwnPropertyNames(currentPrototype);
    // 过滤出函数类型,排除构造函数
    ownProperties.forEach(prop => {
      if (typeof currentPrototype[prop] === 'function' && prop !== 'constructor') {
        methodSet.add(prop);
      }
    });
    // 向上追溯上一层原型
    currentPrototype = Object.getPrototypeOf(currentPrototype);
  }

  return Array.from(methodSet);
}

测试效果

针对你提供的示例代码中的dd实例调用该方法:

const ddMethodList = getAllInheritedMethods(dd);
console.log(ddMethodList); // 输出:["d", "c", "b", "a"],覆盖完整继承链的所有方法

补充说明

  • 如果需要保留子类重写的同名父类方法,不需要去重的话,可以把Set替换为普通数组,直接push方法名即可。
  • 推荐用标准API Object.getPrototypeOf 替代非标准的__proto__属性,兼容性更稳定。
  • 如果需要统计Symbol类型的方法名,可以在遍历时额外加入Object.getOwnPropertySymbols(currentPrototype)的结果一起过滤。

后续生成按钮的参考代码

拿到方法列表后可以直接遍历生成对应的按钮元素:

ddMethodList.forEach(methodName => {
  const btn = document.createElement('button');
  btn.innerText = `调用${methodName}方法`;
  btn.onclick = () => dd[methodName]();
  // 替换为你需要插入的容器节点
  document.body.appendChild(btn);
});

内容的提问来源于stack exchange,提问作者ramonvasquez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:15:02