I have a web component that I created or someone else has created.
And I want to list out all the customMethods created so I can use it later.
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]]();
Your Custom Element can be at the end of a (long) prototype chain,
so you also have to collect the methods of all parent Classes.
If you wanna dive in deeper, do read:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
Quick & dirty code, ignoring anything special you added to your Element instance:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With