How to set javascript private variables in constructor?

One of the best tutorials on private and protected access in javascript is here:

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
var z =;        // not allowed (x has no public property named "bar")

Leave a Comment