Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

ecmascript 5 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...