Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Ignoring

  • Incompetent browsers(browsers that don't support Object.defineProperty)
  • 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?

like image 457
Lime Avatar asked Jul 29 '11 17:07

Lime


People also ask

How do you extend an object in JavaScript?

The extends keyword can be used to extend the objects as well as classes in JavaScript. It is usually used to create a class which is child of another class. Syntax: class childclass extends parentclass {...}

Should works by extending object prototype?

The short answer is Yes, you should do it.

Why is extending built-in JavaScript objects not a good idea?

Extending the JavaScript built-in object is not a good idea because if browser/JS has decided that they will provide the same method that you have extended, then your method will be override and the JS implementation (which may be difference from yours) would take over.

What is difference between __ proto __ and prototype?

prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.


1 Answers

UPDATE from 2021

Despite this being the accepted answer, 10 years of experience has taught me this isn't the best idea. Pretty much anything you can do avoid polluting the global scope is a very very good thing.

Original answer below, for posterity, and because stack overflow will not let me delete an accepted answer.


Original answer from 2011

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.

like image 62
Alex Wayne Avatar answered Sep 28 '22 02:09

Alex Wayne