Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set javascript private variables in constructor?

Say I have a javascript function/class called Foo and it has a property called bar. I want the value of bar to be supplied when the class is instantiated, e.g:

var myFoo = new Foo(5);

would set myFoo.bar to 5.

If I make bar a public variable, then this works, e.g:

function Foo(bar)
{
    this.bar = bar;
}

But if I want to make it private, e.g:

function Foo(bar)
{
   var bar;
}

Then how would I set the value of the private variable bar such that its available to all internal functions of foo?

like image 532
Ali Avatar asked Jul 23 '11 08:07

Ali


2 Answers

One of the best tutorials on private and protected access in javascript is here: 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")
like image 198
jfriend00 Avatar answered Oct 06 '22 19:10

jfriend00


You have to put all functions that need to access the private variable inside the constructor:

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
like image 42
Digital Plane Avatar answered Oct 06 '22 19:10

Digital Plane