Is it ok to define a prototype function on Object in Javascript?

function, javascript, object, prototype

Solution

The only safe way to add to `Object.prototype` is to use the ES5 method `Object.defineProperty` to create a non-enumerable property:

Object.defineProperty(Object.prototype, 'doSomething', {
    value: function(p) { ... },
    enumerable: false,  // actually the default
});

This ensures that the new property doesn't appear if you do `for (key in object)`.

Note that this function cannot be reliably shimmed because non-enumerable properties didn't exist in previous versions of ECMAScript / JavaScript.

In any event, if your method only applies to HTML page elements, you would be better adding this to `Element.prototype` instead of to `Object.prototype`, although older (IE) browsers may complain if you do this.

Problem

``` Object.prototype.doSomething = function(p) { this.innerHTML = "<em>bar</em>"; this.style.color = "#f00"; alert(p); }; document.getElementById("foo").doSomething("Hello World"); ``` `<div id="foo"><strong>foo</strong></div>` The code above works fine. But I remember that I saw this somewhere: `Do not mess with native Object.` well, something like that. So is it ok to define a prototype function on Object? Are there any reasons that I should not do this?

Original source

Related problems