有没有可能的方法通过JavaScript通过其构造函数(最好是HTMLElement
(通过自定义属性或直接访问DOM元素?
类似于下面的代码:
/* Some Attribute
document.body.someAttribute == document.body
(this should be true)
*/
HTMLElement.prototype.someAttribute = (function() {
/* Return the element. */
})();
编辑
显然这就是我要问的:
Object.defineProperty(HTMLElement.prototype, "someAttribute", {
get: function someAttribute() { return this }
});
document.body.someAttribute === document.body // -> true
你的问题很不清楚。您的标题说"访问",但您给出的第一个示例似乎是"测试"。document.body
是HTMLBodyElement
的一个实例,因此它是其构造函数document.body.constructor
的值,所以
document.body.constructor === HTMLBodyElement
和
document.body instanceof HTMLBodyElement
当然还有
document.body instanceof HTMLElement
由于HTMLBodyElement
是HTMLElement
的子类。
您无法从构造函数获取到实例;没有构造函数知道可能用它创建了哪些实例。要查找特定 HTML 元素类型的实例,请使用document.querySelector[All](tagName)
。