0

I add some utils methods to Object class:

Object.prototype.doSomething = function() {
   // do something
};

And now I want to prevent any addition to Object.prototype, is it possible?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
maroodb
  • 1,026
  • 2
  • 16
  • 28
  • You could `Object.freeze` it but...how do you know it wasn't modified *before* this? In fact, how do you know that somebody hasn't replaced `Object.freeze` with an empty implementation? It's (presumably) client-side code, so it's out of your hands. What exactly are you trying to do with preventing modifications? – VLAZ Nov 01 '19 at 16:48
  • 1
    **Note:** Your question suggests your code will be used in contexts that you don't control, e.g., as a library or similar. If so, I **strongly** recommend that you don't modify `Object.prototype` (or any other built-in prototype). It's marginally okay to do so in code you completely control (for instance, your own app), but doing so in a library is a very, very bad idea, as we learned from PrototypeJS and MooTools. – T.J. Crowder Nov 01 '19 at 16:51
  • Is the `[prototypejs]` tag appropriate here? It's related to the Prototype *library*, not about native JavaScript prototypes. Confusion that has plagued the library since it was created. – VLAZ Nov 01 '19 at 16:51
  • isn't about control code, just to be sure that anyone (other developers) override by mistake those methods or add something else. in other world I want that all overrides writen in the some file – maroodb Nov 04 '19 at 15:06

1 Answers1

2

Yes, you can make the object non-extensible and make all of its properties read-only via Object.freeze.

Object.freeze(Object.prototype);

I'd test thoroughly after doing so. :-)


Side note: I'd strongly recommend not using simple assignment to add properties to Object.prototype. Extending Object.prototype at all is usually not recommended, but if you're going to do it, make sure you make the new properties non-enumerable by using defineProperty:

Object.defineProperty(Object.prototype, "doSomething", {
    value: function () {
        // do something
    }
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875