William William - 1 year ago 75
Javascript Question

Extending Object.prototype JavaScript

I am not asking if this is okay:

Object.prototype.method = function(){};

This is deemed evil by pretty much everyone, considering it messes up
for(var i in obj)

The Real Question


  • Incompetent browsers(browsers that don't support

  • Potential for property collision or overriding

Assuming you have some incredibly useful method, is this considered wrong/unethical?

Object.defineProperty(Object.prototype, 'methodOnSteriods',{
value: function(){ /* Makes breakfast, solves world peace, takes out trash */ },
writable: true,
configurable: true,
enumerable: false

If you believe the above is unethical, why would they even implement the feature in the first place?

Answer Source

I think it's fine if it works in your target environment.

Also I think prototype extension paranoia is overblown. As long as you use hasOwnProperty() like a good developer that it's all fine. Worst case, you overload that property elsewhere and lose the method. But that's your own fault if you do that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download