Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 832
user1643156 Avatar asked Mar 25 '13 16:03

user1643156


People also ask

Should you use prototype in JavaScript?

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.

Do all objects have prototype in JavaScript?

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.

How do you set the prototype of one object to another in JavaScript?

The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null .

What's the difference between prototype and __ proto __ in JavaScript?

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.


1 Answers

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.

like image 85
Alnitak Avatar answered Sep 21 '22 16:09

Alnitak