如何在构造函数中设置javascript私有变量?

Cli*_*ote 17 javascript oop scope

假设我有一个调用的javascript函数/类Foo,它有一个名为的属性bar.我希望在bar实例化类时提供值,例如:

var myFoo = new Foo(5);
Run Code Online (Sandbox Code Playgroud)

将设为myFoo.bar5.

如果我创建bar一个公共变量,那么这是有效的,例如:

function Foo(bar)
{
    this.bar = bar;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我想将其设为私有,例如:

function Foo(bar)
{
   var bar;
}
Run Code Online (Sandbox Code Playgroud)

那么我如何设置私有变量的值bar,使其可用于所有内部函数foo

jfr*_*d00 53

关于javascript中私有和受保护访问的最佳教程之一是:http://javascript.crockford.com/private.html.

function Foo(a) {
    var bar = a;                              // private instance data

    this.getBar = function() {return(bar);}   // methods with access to private variable
    this.setBar = function(a) {bar = a;}
}

var x = new Foo(3);
var y = x.getBar();   // 3
x.setBar(12);
var z = x.bar;        // not allowed (x has no public property named "bar")
Run Code Online (Sandbox Code Playgroud)

  • 无论是谁投了这个,你能解释一下原因吗?这对我来说是正确的.+1 (9认同)
  • @GabrielLlamas - 这种方法没有不好的做法.这只是一种权衡.为了实现隐私,您在创建对象时接受微小的性能损失.一旦创建,对象执行完美.原型是为了方便起见.没有理由你必须用它来实现你的目标.如果你创建了很多`Foo()`对象并且性能是最重要的,那么这将是一个糟糕的权衡.但是,如果你只是创建了一对,或者这种方法的表现非常好并且你想要变量隐私,这种方法是一种很好的做法. (7认同)
  • @GabrielLlamas - 我想你不明白这段代码的意义.如果`bar`是真正私有的,那么就无法从外部访问(这是OP要求的),那么它必须被声明为我已经完成了.并且,如果你像我一样声明`bar`,那么你无法从原型上定义的方法访问它.你必须在`bar`范围内定义你的函数.是的,如果你实例化大量的`Foo()`对象,它就不那么有效了,但它是让bar私有化的方法,这就是被问到的问题.请删除你的downvote. (3认同)
  • @GabrielLlamas - 这种获取隐私的方法不是黑客攻击.它使用该语言的支持功能(闭包)来解决最初未设计为该语言的问题.这不是一个黑客 - 它是一个创造性的解决方案,如果需要它提供的功能,使用绝对没有错. (2认同)

Dig*_*ane 23

您必须在构造函数中放置需要访问私有变量的所有函数:

function Foo(bar)
{
  //bar is inside a closure now, only these functions can access it
  this.setBar = function() {bar = 5;}
  this.getBar = function() {return bar;}
  //Other functions
}

var myFoo = new Foo(5);
myFoo.bar;      //Undefined, cannot access variable closure
myFoo.getBar(); //Works, returns 5
Run Code Online (Sandbox Code Playgroud)