Take the 2-minute tour ×

I'm a bit confused, how can I create public and private members.

My code template so far is like:

   var _blah = 1;

   someFunction = function() {

   someOtherFunction = function() {
share|improve this question
You're missing the () after the second function keyword. Should be someOtherFunction = function(). –  user113716 May 10 '10 at 14:24
add comment

5 Answers

up vote 11 down vote accepted

You may want to use the Yahoo Module Pattern:

myModule = function () {

    //"private" variables:
    var myPrivateVar = "I can be accessed only from within myModule."

    //"private" method:
    var myPrivateMethod = function () {
        console.log("I can be accessed only from within myModule");

    return {
        myPublicProperty: "I'm accessible as myModule.myPublicProperty."

        myPublicMethod: function () {
            console.log("I'm accessible as myModule.myPublicMethod.");


You define your private members where myPrivateVar and myPrivateMethod are defined, and your public members where myPublicProperty and myPublicMethod are defined.

You can simply access the public methods and properties as follows:

myModule.myPublicMethod();    // Works
myModule.myPublicProperty;    // Works
myModule.myPrivateMethod();   // Doesn't work - private
myModule.myPrivateVar;        // Doesn't work - private
share|improve this answer
I personally like to define all the functions (public and private) as variables, and then just expose the public ones as myPublicMethod: myPublicMethod. –  stusmith May 10 '10 at 15:24
add comment

You don't. You can rely on convention, prepending _ to your private attributes, and then not touching them with code that shouldn't be using it.

Or you can use the function scope to create variables that can't be accessed from outside.

share|improve this answer
add comment

In javascript every object member is public. Most popular way of declaring the private field is to use the underscore sign in it's name, just to make other people aware that this is private field:

a = {}
a._privateStuff = "foo"

The other way to hide the variable is using the scopes in javascript:

function MyFoo {
    var privateVar = 123;
    this.getPrivateVar = function() {
        return privateVar;

var foo = new MyFoo();

foo.privateVar // Not available! 
foo.getPrivateVar() // Returns the value

Here's the article that explains this technique in details:


share|improve this answer
add comment

Javascript doesn't have true private members. You have to abuse scope if your really need privacy.

share|improve this answer
add comment

Your Answer


