如何将我自己的方法添加到 HTMLElement 对象?
例如,对于 this.parentNode
我想只写 this.p
或代替 document.getElementById('someid')
只需编写document.g('someid')
。当然,这些都是简单的例子,我只是想知道正确的方法是什么。
(我知道我可以使用 jQuery 或 Prototype,但我想了解它是如何在 JS 中完成的)
For example for this.parentNode
I would like to just write this.p
or instead ofdocument.getElementById('someid')
just write document.g('someid')
. Of course that are simple examples, I just want to know what is the correct way to do it.
(I know I can use jQuery or Prototype, but I'd like to learn how it is really done in JS)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尽管您可以在许多浏览器中的
HTMLElement
上构建原型,但Internet Explorer (6,7,8)不是其中之一。 AFAIK,IE9确实支持这个(虽然我还没有测试过)。对于处理它的浏览器,您可以执行以下操作:
Although you can prototype on the
HTMLElement
in many browsers - Internet Explorer (6,7,8) is NOT one of them. AFAIK, IE9 does support this (though I haven't tested it).For browsers that do handle it, you can do:
我强烈建议不要尝试这样做,原因如下:
HTMLElement
原型并允许您对其进行扩充,也不能保证它会按您的预期工作。HTMLElement
原型发生冲突,您将面临命名冲突和难以检测的错误的风险。相反,我建议像 jQuery、YUI 和其他库那样围绕 DOM 节点创建包装对象。
Kangax 写了一篇关于 DOM 可扩展性的好文章,涵盖了所有这些要点等等。
I would strongly suggest not attempting to do this, for a few reasons:
HTMLElement
prototype and allow you to augment it, there's no guarantee that it will work as you expect.HTMLElement
prototype, you risk naming collisions and hard-to-detect bugs.Instead, I would suggest creating wrapper objects around DOM nodes as jQuery, YUI and other libraries do.
Kangax has written a good article on DOM extensibility, covering all these points and more.
一句话,不要。最好不要修改不属于您的对象。
对于
HTMLElement
来说尤其如此,您无法在某些浏览器中修改它。In a word, don't. It is best not to modify objects you don't own.
This is particularly true for
HTMLElement
, which you cannot modify in some browsers.这篇来自perfectionkills.com的文章可能会让您深入了解如何它已经完成了,以及为什么你不应该这样做。
(顺便说一下,jQuery 不扩展 DOM 元素。它们使用 DOM 包装器。)
This article from perfectionkills.com will probably give you some insight into how it's done, and why you shouldn't do it.
(By the way, jQuery doesn't extend DOM elements. They use DOM wrappers instead.)
如果您想包装像
document
这样的全局对象,这可能不是您想要的,但是您可以使用 custom-elements [1] [2] 创建您自己的类似 HTMLElement 的节点。This might not be what you are looking for if you want to wrap a global object like
document
, but you can get a similar effect with custom-elements [1] [2] to create your own HTMLElement-like nodes.