首页 > 解决方案 > 为所有对象创建一个方法,js vanilla?

问题描述

我想创建一个可以从任何对象调用的方法。

例如,我可以创建以下方法:

document.el=function(e){return this.getElementById(e);}

现在我可以打电话了:

document.el("myDiv") //returns <div id="myDiv"></div>

但我想让所有对象都可以使用该方法,所以我可以调用:

document.body.el("myDiv") //returns document.body.el is not a function

我可以从文档的所有子元素中使用它吗?也许通过递归循环?基本上我正在寻找的是类似的东西:

*.el=function(e)...

标签: javascriptfunctionobjectmethodschildren

解决方案


尽管您可能不应该扩展 DOM,但您可以通过向 的原型添加方法来实现HTMLElement,例如:

HTMLElement.prototype.el = function (id)  {
  return this.getElementById(id);
};
<div id='div-id'><p id='p-id'>Hello</p></div>
document.getElementById('div-id').el('p-id').innerText; // `Hello`

推荐阅读