Code at the bottom of exercise 25


#1


https://www.codecademy.com/en/courses/objects-ii/4/4?curriculum_id=506324b3a7dffd00020bf661#

I understand what's going on here in terms of the methods in the object constructor but I'm slightly confused with what's going on at the bottom of the code, where the same method seemingly needs to be called twice in order to work.

It it loosely explained in the instructions "Because askTeller returns a method, we need to call it to make it any use. This is what var myBalance = myBalanceMethod(); does."

To my understanding the previous exercise (24) also required calling a method but in that case calling it the once was sufficient (the equivalent code in that exercise being var myBalance = john.getBalance();
console.log(myBalance); )

Why then this time do we need:

var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();

console.log(myBalance);

Many thanks,

Will


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

You're not calling the same value twice, you're calling a function which returns another function

function f() {
  function g() {
    return 5;
  }
  return g;
}

f()();  // calling (the result of calling f) returns 5
        // (the result of calling f is a function)

#3

Thank you for the explanation, I am close to grasping this I think...

So effectively is:

var myBalanceMethod = john.askTeller();

calling the john.askTeller function, and then:

var myBalance = myBalanceMethod();

calls the returnBalance function returned by john.askTeller after that first call?


#4

Yeah. Something more intuitive might be a function that returns an action, like adding or subtracting:

function getOperator(sign) {
    let operators = {
        '+': function(a, b) { return a + b; },
        '-': function(a, b) { return a - b; }
    };

    return operators[sign];
}

getOperator('+')(5, 3);  // 8
getOperator('-')(5, 3);  // 2

Probably not the best design to create the function objects each time that function is called.. That's a bit beside the point though.