我想防止变量被更改。特别是对象的属性:
var foo = { bar: 'baz' };
// do something to foo to make it readonly
foo.bar = 'boing'; // should throw exception
这可以做到吗?
我想防止变量被更改。特别是对象的属性:
var foo = { bar: 'baz' };
// do something to foo to make it readonly
foo.bar = 'boing'; // should throw exception
这可以做到吗?
你可以试试
Object.defineProperty(foo, "bar", { writable: false });
并且后面的分配要么静默失败,要么如果您处于严格模式,则会引发异常(根据 David Flanagan 的“JavaScript : The Definitive Guide”)。
使用一个函数:
var foo = function() {
  var bar = 'baz';
  return {
    getBar: function() {
      return bar;
    }
  }
}();
这样 foo.bar 是未定义的,您只能通过 foo.getBar(); 访问它
看这个例子:
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