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?
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
Each and every JavaScript function will have a prototype property which is of the object type. You can define your own properties under prototype . When you will use the function as a constructor function, all the instances of it will inherit properties from the prototype object.
The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null .
The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With