Extending Object.prototype JavaScript

前端 未结 5 504
终归单人心
终归单人心 2020-11-27 05:30

I am not asking if this is okay:

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

This is deemed evil by pretty much everyone, cons

5条回答
  •  萌比男神i
    2020-11-27 06:23

    I'd say this is almost as evil as before. The biggest problem, still the same as before, is that Object.prototype is global. While your method might currently be solving world peace, it might have overwriten someone else's method (that was guaranteeing galactic peace) or may be overwritten in the future by some library you have no control over (therefore plunging the world into chaos again)


    New versions of Javascript have lots of features related to properties, such as definig a property to be enumerable/not enumerable, having getters and setters... Object.defineProperty existis to give control over this.

    From Mozilla Docs:

    This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults.


    This new function is basically required to support the new features and you are supposed to use it on your own stuff. Being able to modify Object.prototype is just a side effect of it also being a "normal" object and is just as evil as before.

提交回复
热议问题