Tuesday, April 23, 2013

Javascript: Private and Public


All properties in JavaScript are automatically public, which means that they can be accessed outside of the class. Look at the Person class below. It has three properties: firstName, lastName, and age. Think of these properties as the information a class is willing to share.

 On lines 8 and 9, we access the firstName and lastName properties of john and assign them myFirst and myLast. Note that we are free to access the firstName, lastName, and age properties, which is what we mean when we say that they are public.

function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
}

var john = new Person( 'John', 'Doe', 30);
var myFirst = john.firstName;
var myLast = john.lastName;
var myAge = john.age;

Yay! But what if an object wants to keep some information hidden? Remember local variables? (--They can only be accessed from within that function!) Well functions can also have private variables which are pieces of information that can only be directly accessed from within the class.

Here, the Person class has been modified to have a private variable called bankBalance. Notice that it looks just like a normal variable except that it is defined inside the constructor for Person, without using this, but instead using var. This makes bankBalance a private variable.


function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    var bankBalance = 7500;
}


We we try to print his bankBalance out, all we get is undefined.

Methods can also be private within a class and inaccessible outside of the class. Changing this.returnBalance from the last exercise to var returnBalance makes this method private. The way to access a private method is similar to accessing a private variable. You must create a public method for the class that returns the private method.

var returnBalance = function() {
    return bankBalance;
};
this.askTeller = function() {
    return returnBalance;
};

var john = new Person('John', 'Doe', 30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

The askTeller function has been modified within the Person class to directly give you your balance. However, it now needs the account password parameter in order to return the bankBalance.


function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
 
   this.askTeller = function(pass) {
     if (pass == 1234) {
        return bankBalance;
     }
     else {
        return "Wrong password.";
        }
   };
 
   var myBalance = function(pass) {
       return askTeller;
   };
}

var john = new Person('John','Doe',30);
/* the variable myBalance should access askTeller() with a password as an argument  */

No comments:

Post a Comment