csha
csha

Reputation: 9584

js - Freeze current properties

Is there a way to freeze existing properties of an object allowing to add new properties to it?

Hello World,
I've got an window.foo object with properties bar=1 and qux=2.
I need these to be frozen and unrewritable.

It's easy using this code:

var foo = {};
Object.defineProperty(foo,"bar",{ "value":1 });
Object.defineProperty(foo,"qux",{ "value":2 });

But this can be easily overwritten by window.foo={"bar":3};.

Is there any way?

Thanks :)

Upvotes: 1

Views: 278

Answers (2)

csha
csha

Reputation: 9584

Yeah, I think I've got it.
The key is that non-writable property which is an object still can be modified (adding properties etc.) because the "non-writable thing" about it is just the object's address.
I didn't know this, now it turns out it's quite easy!

//non-writable window.foo
Object.defineProperty(window,"foo",{
 "enumerable":true,
 "value":{}
});

//Non-writable foo.bar
Object.defineProperty(window.foo,"bar",{
 "enumerable":true,
 "value":1
});

//Non-writable foo.qux
Object.defineProperty(window.foo,"qux",{
 "enumerable":true,
 "value":2
});

And here it is! :)
Thank you for your help.

Upvotes: 2

Adam Jenkins
Adam Jenkins

Reputation: 55643

No, but you can define all current properties to make them not writable and not configurable, which will accomplish the same task.

Object.prototype.freezeAllCurrentProperties = function() {
  for(i in this) {
   if(this.hasOwnProperty(i)) {
     Object.defineProperty(this,i,{writable:false,configurable:false});
   }
  }
}

var x = {'firstProp':'a string'};
x.freezeAllCurrentProperties();
delete x['firstProp']; //returns false (thanks to configurable:false)
x['firstProp'] = false; //doesn't change (thanks to writable:false)
x.newProp = true; //adds newProp to x

Upvotes: 0

Related Questions