Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a variable be made readonly in Node.js

I want to prevent a variable from being changed. Specifically a property of an Object:

var foo = { bar: 'baz' };

// do something to foo to make it readonly

foo.bar = 'boing'; // should throw exception

Can this be done?

like image 398
EvdB Avatar asked Feb 17 '26 02:02

EvdB


1 Answers

You could try

Object.defineProperty(foo, "bar", { writable: false });

and the later assignment either fails silently or, if you are in strict mode, throws an exception (according to David Flanagan's "JavaScript : The Definitive Guide" ).

like image 58
lmsteffan Avatar answered Feb 18 '26 17:02

lmsteffan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!