Reputation: 1971
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
Date.prototype.name="not good";
var d=new Date();
document.getElementById("demo").innerHTML =d.name;
</script>
</body>
</html>
Result-
not good
In the above example the name field is being added to the Data object using the prototype functionality.
What could be the drawbacks of doing this? Are the changes made here will reflect permanently?
According to w3scholls I got this note- Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
But sometimes isn't it convenient?
Upvotes: 0
Views: 124
Reputation: 707318
Except for polyfills which implement standard-defined behavior in older implementations, it is generally not considered a good practice to modify the implementation of built-in objects. These are some of the reasons:
A standard object is a public namespace. The standards may evolve over time and add new methods/properties which could conflict with the properties you add. Better to avoid that possibility and avoid code that could conflict with future browsers.
If multiple pieces of code being used in a project are all doing this (imagine a project that pulls in 15 third party libraries to do its job), then there is a chance for conflict among the modifications (since they aren't defined by any standards).
You may be modifying the behavior of a standard object in a way that could break some existing code. For example, adding an enumerable property or method to some objects can mess up existing code that iterates existing properties. If you were going to add something, make sure you add it with Object.defineProperty()
so that it is not enumerable.
There's pretty much always another way to accomplish what you want to do that doesn't have these risks and works just as well. For example, jQuery chooses to create a container wrapper (it's own object) that contains references to DOM objects and is the container object for its own methods.
Upvotes: 3