如何获取Web Component上所有可用的公共自定义方法
获取自定义Web Component实例的所有自定义方法
你当前用Object.keys(instance)无法拿到自定义方法的原因是:ES6 class 语法中声明的类方法默认挂载在类的原型对象上,且属性描述符为不可枚举,Object.keys只能读取实例自身的可枚举属性,自然拿不到原型上的方法。
你可以用下面的通用工具函数实现需求:
function getCustomElementMethods(instance) { // 提前收集HTMLElement内置的所有属性,做排除用 const builtInProps = new Set(Object.getOwnPropertyNames(HTMLElement.prototype)) // 获取自定义元素对应的原型对象 const customProto = Object.getPrototypeOf(instance) return Object.getOwnPropertyNames(customProto).filter(prop => { // 仅保留自定义的方法,排除内置方法和非函数属性 return typeof instance[prop] === 'function' && !builtInProps.has(prop) }) } // 用你提供的示例代码测试 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' ) const methods = getCustomElementMethods(instance) // 输出 ['customMethod1', 'customMethod2'] console.log(methods) // 按你的需求调用即可 instance[methods[0]]()
如果你的自定义元素存在多层继承的情况(比如自定义类继承了另一个自定义基类),可以用下面支持遍历原型链的版本:
function getAllCustomElementMethods(instance) { const builtInProps = new Set(Object.getOwnPropertyNames(HTMLElement.prototype)) const customMethods = [] let currentProto = Object.getPrototypeOf(instance) // 遍历原型链直到碰到内置HTMLElement的原型就停止 while (currentProto !== HTMLElement.prototype) { Object.getOwnPropertyNames(currentProto).forEach(prop => { if ( typeof instance[prop] === 'function' && !builtInProps.has(prop) && !customMethods.includes(prop) ) { customMethods.push(prop) } }) currentProto = Object.getPrototypeOf(currentProto) } return customMethods }
内容的提问来源于stack exchange,提问作者Reuel Teodoro
相关产品推荐
相关产品推荐

