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?
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" ).
Use a function:
var foo = function() {
var bar = 'baz';
return {
getBar: function() {
return bar;
}
}
}();
In that way foo.bar is undefined, you can only access it through foo.getBar();
Look at this example:
var Foo = function(){
this.var1 = "A"; // public
var var2 = "B"; // private
this.getVar2 = function(){ return var2; }
}
var foo = new Foo();
console.log(foo.var1); // will output A
console.log(foo.var2) // undefined
console.log(foo.getVar2()) // will output B
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.