25. Private Methods


#1



Hello.Code works but i can't understand why in the "askTeller" method we use "this" and not "john" and why we don't use "var".


function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   var returnBalance = function() {
      return bankBalance;
   };
       
   // create the new function here
   this.askTeller = function() {
       return returnBalance;
   };
}

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


#2

@warriorcodes

Hi,

  1. We are using this not john because you might be creating other person and their name might not be john! this is telling Javascript that whichever person we are creating will get this method.
  2. We are not using var keyword because we are creating a method inside of a class

#3

Oh thank you.So when building method inside a class we are not using var.When outside we do?


#4

@warriorcodes

Yes. Functions and methods are different. Method belongs to a class and only applicable to the instance associated with it while functions can be called at any time.


#5

I'm kinda getting the difference between a Function and a method but why did they prompt us in the exercise " // create the new function here" they called if a "function"? Wouldn't it been more accurate to say "create the new method here"?