Can you explain me this outputs?


#1
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 =  returnBalance;
}

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

And outputs: ( Why john.askTeller == [Function] but john.askTeller() not? )

[Function]
TypeError: myBalanceMethod is not a function

#2

@webrunner42786,

You will have to change

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

#3

I know, but i'm interested in explanation why this doesn't works this way?


#4

Hi,
I have tried a little bit..It might help us..
If U want to assign

    this.askTeller = returnBalance;    /*as we have did in Object1...'this' method*/

Then, You have to do a small change in last 4 lines..
As You are asssigning john.askTeller() to a variable (myBalanceMethod)

var myBalanceMethod = john.askTeller();

And again assigning myBalanceMethod to another variable.. Which will shoot error..

So, Simply assign john.askTeller(); to var myBalance directly.

var myBalance = john.askTeller();

Here.

john.askTeller = returnBalance;   /* is function referencing */

while

var myBalanceMethod = john.askTeller();   /* is function calling  */

#5

But here the console is in search of returnBalance statement..

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

So it will throw error untill it finds it..