Skip to content Skip to sidebar Skip to footer

What Are Pitfalls Of Extending Object.prototype?

I want to extend Object.prototype, to basically support notifications in JSON data and html elements through UI framework. Object.prototype.setValue = function(key,value){ // th

Solution 1:

I know it fails for(var x in obj), but mostly we can use obj.hasOwnProperty, that should help right?

That is the only major pitfall, and .hasOwnProperty() helps, but only in your own code. In jQuery, for example, they've taken the deliberate decision not to call .hasOwnProperty in the $.each() method.

I have used Object.defineProperty(...) in my own code to get around the enumerable property problem with no ill-effects (albeit on Array.prototype)

Solution 2:

You just don't want to mess with prototypes from host or native objects.

  • You cannot know which side effects it has on any third-party script
  • You may confuse third party code
  • You don't know if some day those methods are created natively

overall, extending Object.prototype effects any other object on the entire site. Again, you just don't want to do it, unless, you are in such a sandboxed environment and every single piece of ecmascript is written on your own and you are 100% sure no third-party script is ever loaded.

Post a Comment for "What Are Pitfalls Of Extending Object.prototype?"