简体   繁体   English

可以在Node.js中只读变量

[英]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? 可以这样做吗?

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" ). 并且后面的分配要么默默失败,要么在严格模式下抛出异常(根据David Flanagan的“ JavaScript:权威指南”)。

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(); 这样,foo.bar是未定义的,您只能通过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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM