-2

I'm trying to freeze below object without using Object.freeze() is it possible to do so ?

const obj = {
  a:'test',
  b:'Something'
}
Aniket
  • 127
  • 1
  • 11
  • 3
    Any specific reason to not use `freeze()`? – Jud Aug 11 '21 at 17:24
  • 1
    What are you trying to achieve with this code? – Dennis Kozevnikoff Aug 11 '21 at 17:25
  • 1
    Does this answer your question? [Implement alternative to Object.seal, Object.freeze, Object.preventExtensions](https://stackoverflow.com/questions/37387077/implement-alternative-to-object-seal-object-freeze-object-preventextensions) – Jud Aug 11 '21 at 17:25
  • 2
    @JakenHerman Just out of curiosity ! – Aniket Aug 11 '21 at 17:26
  • 2
    Does this answer your question? [Javascript: Object doesn't support method 'freeze'](https://stackoverflow.com/questions/13117771/javascript-object-doesnt-support-method-freeze) – Heretic Monkey Aug 11 '21 at 17:29

1 Answers1

3

Not literally, no. Object.freeze sets the integrity level of the object to frozen, which you can't do in another way.

You can do most of the things that make an object "frozen" separately, though, by using Object.preventExtensions to prevent properties being added and the combination of Object.getOwnPropertyDescriptor and Object.defineProperty to prevent properties being modified or removed. I don't think you can prevent its prototype being changed via Object.setPrototypeOf, though, which is another aspect of frozen objects. (You could interfere with setting the __proto__ property inherited from Object.prototype [if the object inherits from Object.prototype], but that wouldn't have any effect on Object.setPrototypeOf.)

But you can't actually set the integrity level of the object like Object.freeze does.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • is it possible to freeze object without using any pre-defined function's of JS ? – Aniket Aug 11 '21 at 17:47
  • 3
    @Aniket the answer states that it's not possible. – VLAZ Aug 11 '21 at 18:18
  • 1
    @Aniket - No, `Object.freeze` is the only way to actually freeze an object. And you can't even get close without them. For instance, you can't define a non-configurable property without one of the `Object` methods. – T.J. Crowder Aug 11 '21 at 21:17