Reputation: 185973
I know how to add new methods to every object - by augmenting the Object's prototype:
Object.prototype.foo = function() { };
But, is it possible to define new methods for DOM element nodes only? Do DOM element node objects have a prototype? Or is there maybe a prototype for DOM nodes in general?
Or do prototype objects only exist for built-in objects?
Upvotes: 12
Views: 19744
Reputation: 344695
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.
Upvotes: 30
Reputation: 21690
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 DOM
Object.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.
Upvotes: 2
Reputation: 324627
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.
Upvotes: 4