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){
// 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, Extending Object.prototype JavaScript and few others, people say that we should avoid extending Object.prototype, instead any other type is fine.
If I do not do this, then my code becomes bigger, for example
window.myModel.setValue("currentStatus","empty");
will have to be written like,
Binder.setValue(window.myModel,"currentStatus","empty");
I want to know what will go wrong if I use these methods? will it cause jQuery to behave unexpectedly? I have seen once, that jQuery's ajax request invokes prototype methods as well (as they references to functions for event handling).
What are other side effects of this? I know it fails for(var x in obj), but mostly we can use obj.hasOwnProperty, that should help right?
You just don't want to mess with prototypes from host or native objects.
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.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 onArray.prototype
)