0

I want to create a closed object in javascript, that can be edited only using Object.defineProperty and not to be edited it in the normal way...

The goal is, I am creating a lib, where users can read an object called dictionary, but they can edit it too! is there any way to have an object that can be read by users, and edited by me ?

challenger
  • 2,184
  • 1
  • 18
  • 25

3 Answers3

0

It is just not possible to protect any object parts.

See also: How to Create Protected Object Properties in JavaScript

Community
  • 1
  • 1
edi
  • 917
  • 7
  • 17
0

You can provide some basic protection using Object.defineProperty like this:

var o = { a: 5 };

o._protected = {};
o._protected.a = o.a;
Object.defineProperty(o, 'a', {
  get: function() { return this._protected.a; },
  set: function(value) {
   if (value > 0 && value < 5) {
     this._protected.a = value;
   }
  configurable: false
});

This will constrain changes to property a in this object so they will go through the get (read) / set (update). Of course, in this case the _protected object can be manipulated but it does require the user to consciously 'hack' it. Attempts to directly change property a would be under your control.

In this example, an attempt to set o.a = 6 would result in no change to o.a (of course, you could set it to the maximum allowed value in your set function if that were preferable).

You can prevent changes to o.a by not providing a set function.

This can be handy for ensuring properties only get 'valid' values and I've often used it that way.

rasmeister
  • 1,986
  • 1
  • 13
  • 19
0

I found it! please tell me what's the wrong with this solution:

   var protected = {}

   Object.defineProperty(this,
     'setter', {
       value: function(name , value) {
         protected[name] = value
       },  
       writable: false,                                               
     })  

   Object.defineProperty(this,
     'getter', {
       value: function(name , value) {
         return JSON.parse(JSON.stringify(protected))
       },  
       writable: false,
     })  

  Object.freeze(this.setter)
  Object.freeze(this.getter)
challenger
  • 2,184
  • 1
  • 18
  • 25