Monday, June 3, 2013

javascirpt lesson 10 -- continued

In javascript, by default all properties of an object are public.

Just as functions have local variables, which can be accessed only from inside a function. we can also have private variables in a class which we won't share publicly.

if create a variable without using 'this' keyword in a constructor function, then it is a private variable.

ex :

function Person(name){
this.name = name;
var balance = 234;
}

var sur = new Person("bob");
console.log(sur.balance); // not accessible, gives undefined output

*** Even though we cannot access private variables directly, we can access them by using a public method. this method is very similar to access a private variable.
ex:


function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;

   this.getBalance = function() {
      // your code should return the bankBalance
      return bankBalance;
   };
}

var john = new Person('John','Smith',30);
console.log(john.bankBalance);

// create a new variable myBalance that calls getBalance()
var myBalance = john.getBalance();
console.log(myBalance);

A method can return another method inside a method.
ex:

this.askTeler = function(){
       return returnBalance();
   };

********** types of variables we are concerned with are 'number' 'string' and 'object'

No comments:

Post a Comment