如何获得 Web 组件上可用的所有 public 方法

How do I get all the public methods available on a web component

我有自己创建的或其他人创建的 Web 组件。

我想列出所有创建的自定义方法,以便稍后使用。

class CustomElement extends HTMLElement {
  customMethod1() {
    console.log( 'customMethod 1 called' )
  }

  customMethod2() {
    console.log( 'customMethod 2 called' )
  }
}

customElements.define( 'custom-el', CustomElement )

const instance = document.createElement( 'custom-el' )



// Something like this

const methods = Object.keys(instance);



// So I can do this later

instance[methods[0]]();

您的自定义元素可以位于(长)原型链的末尾,
所以你还必须收集所有父 类.

的方法

如果您想深入了解,请阅读:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

快速而肮脏的代码,忽略您添加到元素中的任何特殊内容 实例:

<script>
  class BaseClass extends HTMLElement {
    baseMethod2() {}
    baseMethod1() {}
  }
  customElements.define('custom-element', class extends BaseClass {
    customMethod1() {}
    customMethod2() {}
  });

  function getMethods(el) {
    let methods = [];
    (function examinePrototype(obj) {
      let isInstance = obj === el;
      let obj_constructor = obj.constructor;
      let obj_prototype = obj_constructor.prototype;
      let class_methods = Object.getOwnPropertyNames(obj_prototype);
      let descriptors = Object.getOwnPropertyDescriptors(obj_prototype);
      let name = isInstance ? "Instance" : obj_constructor.name || "Inline Class";
      console.log(name, "methods:", class_methods.join(", "));
      //console.log("descriptors",descriptors);
      if (!isInstance) methods.push(class_methods);
      // a bit blunt, but works for Autonomous Custom Elements:
      let isHTMLElement = descriptors.constructor.value.toString().includes("HTMLElement");
      if (!isHTMLElement) examinePrototype(Object.getPrototypeOf(obj))
    })(el); // IIFE
    return methods.flat().filter(x => x != "constructor");
  }
  let element = document.createElement('custom-element');
  let element_methods = getMethods(element);
  console.log("element methods:", element_methods.join(", "));
</script>