我想获得一个 HTML 元素的所有属性、样式、事件和方法的列表。浏览器有反射API吗?
我正在寻找这样的东西:
var button = new HTMLButtonElement();
var className = document.getQualifiedClassName(button); // "HTMLButtonElement"
var definition = document.getDefinition(className); // HTMLButtonElement reference
var instance = document.getInstance(definition); // instance of HTMLButtonElement
var properties = document.getProperties(button); // properties of HTMLButtonElement
var methods = document.getMethods(button); // methods of HTMLButtonElement
var styles = document.getStyles(button); // styles applicable to HTMLButtonElement
var events = document.getEvents(button); // events on HTMLButtonElement
var inheritance = document.getInheritance(button); // HTMLButtonElement > HTMLElement
编辑:
这是 ActionScript3 中的调用,它获得了我正在寻找的内容:
var objectInformation = document.describeType(button) // metadata
这可能会使我在 JavaScript 中尝试做的事情更加清楚。
背景
假设我正在尝试将完整的代码添加到 HTML 代码编辑器中。当用户将光标放在 div 元素旁边并启动代码完成时,我想向他们显示代码完成弹出窗口中的所有事件、属性和样式。当他们输入 JavaScript 时,我想自动完成所有可用的方法。当他们开始输入样式对象时,我想提供一个样式列表。
如果我得到一个对象或标签名称,我需要能够显示代码完成的所有元数据。在许多语言中都有 API 可以执行此操作。
最佳答案
没有什么比AS3's describeType
在 JS 中。您同时要求很多东西,其中一些可以在 JS 中获得,而另一些则不能(其中一些在 JS 中甚至可能没有意义,因为它是如此动态。)
您可以使用Object.getOwnPropertyDescriptors()
当然可以获取对象及其层次结构的属性和方法。和 Object.getPrototypeOf()
.
function describeType(object) {
const prototype = Object.getPrototypeOf(object);
console.log("Hello, I am a", prototype.constructor.name);
console.log("My properties are", Object.getOwnPropertyDescriptors(object));
console.log("My prototype proterties are", Object.getOwnPropertyDescriptors(prototype));
const superPrototype = Object.getPrototypeOf(prototype);
if (superPrototype) {
console.log("My super class is", superPrototype.constructor.name);
// etc
}
}
关于javascript - 浏览器中的JavaScript有反射机制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42464292/