Augmenting The Prototype Of Dom Element Nodes?
Solution 1:
Yes, but not in all browsers. Internet Explorer 8 supports DOM prototypes (to a certain extent), as do Firefox, Chrome, Opera and Safari.
HTMLElement.prototype.toggle = function () {
this.style.display = this.style.display == 'none' ? '' : 'none';
}
Many consider it bad practice to extend DOM objects via their prototype. Kangax has a great article on the subject: http://perfectionkills.com/whats-wrong-with-extending-the-dom/. However, DOM prototypes allow us to implement standards-based methods in environments that don't support them yet, much like shims for ECMAScript 5th Edition methods.
Solution 2:
In some browsers, DOM elements do expose a prototype object, which may also inherit from Object.prototype
, but this is not universally true (for example, IE does not). In general, host objects such as DOM elements are not obliged to do this; in fact, host objects are not bound by many of the rules that apply to native JavaScript objects, so you should never rely on DOM elements to support this kind of thing.
I recommend kangax's excellent article on this subject.
Solution 3:
That's exactly what prototype.js does, but is now considered extremely bad practise.
It's much better to use wrappers/handlers. Note, augmenting ANY native objects, especially the Object
object, is bad practise.
read:
Whats wrong with extending the DOMObject.prototype is verboten
Addendum:
Whilst extending native objects in small projects it can be considered safe it will actually become an extremely bad habbit. It's only marginally less worse then littering the global scope with functions and variables. Not only do name collisions occur, but also implementation collisions. This will become more apearant the more libraries you mash up.
Keeping your implementation on your own objects is the only way to avoid ANY collisions, name, implementation or otherwise.
All that said, it's your perogative to do as you please, I however will not recommend anything thats widely accepted as sheer bad practise. I stick to my recommendation.
Post a Comment for "Augmenting The Prototype Of Dom Element Nodes?"