Skip to content


Javascript – Private Variables How To

One seemingly difficult task in javascript is creating private variables within a class. Quite a few programmers will signify a private variable or method with an _ (underscore) prefix, however this does not solve the problem of making the variable truly private.

You can make variables private by enclosing them within a classes constructor. Below you will find a very generic example of how to accomplish this.

First declare the classes constructor.

//constructor
var myClass = function() {
    var myPrivateVar = "test";
 
    //create a setter function
    this.setMyPrivateVar = function(val) {
        myPrivateVar = val;
    }
 
    //create a getter function
    this.getMyPrivateVar = function() {
        return myPrivateVar;
    }
}

Now, within the body of the class, in order to access the private variables you will need to use the accessor methods.

myClass.prototype = {
    doSomething: function() {
        alert(this.getMyPrivateVar());
    }
};
 
var example = new myClass();
example.doSomething(); //shows alert w/ test
alert(example.myPrivateVar); //undefined, private cannot access
alert(example.getMyPrivateVar()); //shows alert w/ test

Any values you want to behave in a private manner should be placed in the class constructor and accessed via your accessor methods.

Happy Coding.

Posted in Javascript.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.