I don't understand part of this code


#1

I am on Exercise 25: Private Methods.

In the code below, I have bolded (put asterisks around) and italicized the two lines that I am confused about.
What exactly does the first bolded line do? How would you explain it, exactly?

In the second bolded line, why does myBalanceMethod() have the parenthesis? it's not actually a defined method, right?

function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
  
   var returnBalance = function() {
      return bankBalance;
   };
       
   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

Actually, it is. john.askTeller() returns a method, in the form of a string. myBalanceMethod() invokes it and stores the return value in myBalance.


#3

Ok, so because myBalanceMethod = a method, it becomes a method itself?

Is it the same as saying: var myBalanceMethod = function() but replacing the word "function" with the actual name of the method? (I hope that made sense...)


#4

Sort of. Consider the following:

var ageSet = function () {
    return function (newAge) {
    this.age = newAge;
};
};

var bob = {};

bob.setAge = ageSet();

var doc = bob.setAge.toString();

console.log(doc);

Output

function (newAge) {
    this.age = newAge
}

Now comes the thinking part. This function, when returned from another function is a closure that includes its own execution context and scope. Everything it needs to function is included, save for external arguments. In this case, newAge needs to be passed.

bob.setAge(25);
console.log(bob.age);    // 25

In the myBalance example above no arguments are supplied. Just a call to the function that can access the private variables encapsulated within the closure.

console.log(bob);       // { setAge: [Function], age: 25 }

Remember when we defined bob? As an emply object?

bob is an execution context since it is an object, this is the function that sorts out that the execution context is bob. age is a property in the same scope as this, so it is encapsulated as this.age which translates to bob.age in this instance.


#5

Ok, got it now!
Thank you very much for your help and for explaining everything.
I really appreciate you taking the time to do that.


#6

You're welcome! It's a pleasure whence we succeed.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.