What are the pitfalls of the Object.prototype extension?

I want to extend Object.prototype to basically support notifications in JSON data and html elements through the user interface infrastructure.

Object.prototype.setValue = function(key,value){ // this simply sets value as this[key] = value // and raises an event Binder.setValue(this,key,value); }; Object.prototype.getValue = function(key){ return Binder.getValue(this,key); }; 

However, based on this question, the Object.prototype JavaScript Extension and several others, people say that we should avoid the Object.prototype extension, instead, any other type is fine.

If I do not, then my code will become larger, for example

 window.myModel.setValue("currentStatus","empty"); 

should be written like

 Binder.setValue(window.myModel,"currentStatus","empty"); 

I want to know what will go wrong if I use these methods? will this cause jQuery to behave unexpectedly? I saw once that jQuery ajax request also calls prototype methods (as they refer to event processing functions).

What are the other side effects of this? I know this fails (var x in obj), but basically we can use obj.hasOwnProperty, which should help correctly?

+3
javascript object prototype-programming
Dec 01 '11 at 12:08
source share
2 answers

You just don't want to mess with prototypes from the host or your own objects.

  • You may not know what side effects it has on a third-party script
  • You can confuse third-party code
  • You do not know someday will create these methods initially

in general, expanding the Object.prototype effects of any other object throughout the site. Again, you just don’t want to do this unless you are in a sandboxed environment and each piece of ecacccript is written on its own, and you are 100% sure that no third-party script will be loaded.

+1
Dec 01 '11 at 12:16
source share
β€” -

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

This is the only major mistake, and .hasOwnProperty() helps, but only in your own code. For example, in jQuery they made the intentional decision not to call .hasOwnProperty in the $.each() method.

I used Object.defineProperty(...) in my own code to get around the enumerated property problem without any side effects (albeit on Array.prototype )

+2
Dec 01 '11 at 12:14
source share



All Articles