Skip to main content

Forums

  • This topic is empty.
Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #198253
    porgeet
    Participant

    Hi guys and girls

    I’m doing some courses on Codecademy to teach myself Javascript, every now and then I’ll complete a course but I’m not entirely sure what the code does, or why it’s done that way.

    This particular course is teaching me about variables being private or public within an object. And how to access something that has been made private using the var keyword. In this case it’s the private returnBalance function.

    I was hoping you good people could shed some light on it for me please?

    Here is the code:

    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);
    

    I’m puzzled by the bottom part where I console.log the method askTeller.

    I’m not sure why I can’t just console.log(john.askTeller());

    I’m also not sure why john.askTeller(); assigned the variable myBalanceMethod then that variable is assigned to the variable myBalance to then be console.log();ed.

    Any explanation or pointing in the right direction would be greatly appreciated.

    Thanks
    porgeet

    #198273
    Chromawoods
    Participant

    The return value you get when calling john.askTeller() is a function itself, which is why you first store it in myBalanceMethod. You could call it directly by doing john.askTeller()() but that’s a bit weird.

    I’m not sure what the restrictions of this particular course are, but instead of askTeller returning return returnBalance; you could instead return the result of it: return returnBalance();. But again, I don’t know if that would violate what the course is trying to teach you.

    #198283
    porgeet
    Participant

    Thanks for your help.

    You pretty much just do what you’re told in it, it can be quite limited in the amount of wiggle room you have to experiment.

    It just teaches you that object keys can be accessed from outside the object. As soon as you use the var keyword their local scope makes them effectively private.

    You can do the same with functions defined within the object constructor.

    Then it teaches you that you can make something access an object’s keys using a function without the var keyword.

    The bottom code was populated by the course itself, but the explanation of why it’s made like that is not very clear.

    The way I understand it there is a difference between calling a function(); where the function would be activated expecting arguments etc.? And calling the function’s outputted value where you would exclude the ().

    Is that why the bottom part of the code is the way it is?

    If so why not just console.log(myBalanceMethod);?

    Does setting var myBalanceMethod = john.askTeller(); create an empty function called myBalanceMethod();, then setting a variable equal to that function var myBalance = myBalanceMethod(); creates a variable equal to all of that, so that it can then be console logged without calling it?

    It looks to me like it’s just a way to get around having to call the function and just console log it’s result which is already going to be set.

    That’s my understanding so far :P

    Sorry about the verbose post

    Thanks again for your help
    porgeet

    #198288
    __
    Participant

    This reply has been reported for inappropriate content.

    The way I understand it there is a difference between calling a function(); where the function would be activated expecting arguments etc.? And calling the function’s outputted value where you would exclude the ().

    The () is “calling” the function. Without it, you’r just working with the variable the function is assigned to (it’s “name tag,” if you will).

    Does setting var myBalanceMethod = john.askTeller(); create an empty function called myBalanceMethod();, then setting a variable equal to that function var myBalance = myBalanceMethod(); creates a variable equal to all of that, so that it can then be console logged without calling it?

    • `var myBalanceMethod = john.askTeller();`
      You’re calling the method and assigning its result. `myBalanceMethod` is the return value of `john.askTeller()`, i.e., the object’s `returnBalance` function.
    • `var myBalance = myBalanceMethod();`
      Likewise, `myBalance` is the return value of `myBalanceMethod` — the object’s `bankBalance` property.

    The part you seem to be “missing” is that calling a function gives you its result (its return value). If you assign a function without invoking it, you’re just handling the function object itself.

    // foo is the variable that the function is assigned to.
    // "foo!" is the function's return value.
    var foo = function(){ return "foo!"; };
    
    var fooTwo = foo;
    // fooTwo is a second variable that is assigned the same function.
    //  NOTE, this is _literally_ the same function object as foo.
    
    var saidFoo = foo();
    // invoking (calling) the function gives us the return value:
    //  here, a string, "foo!".
    

    new example, closer to what you’re asking about:

    // fooMaker creates foo functions.
    //  this pattern is called a _factory_.
    var fooMaker = function(){
    
        // foo is a local ("private") variable,
        //  which is assigned a function.
        var foo = function(){
            return "foo!";
        };
    
        // fooMaker's return value is the foo function.
        return foo;
    };
    
    // if you want a foo, ask the fooMaker for one.
    var myFoo = fooMaker();
    
    // if you want to know what foo says, invoke (call) it.
    var fooSays = myFoo();
    

    Here’s something a bit more useful:

    // fooMaker is the same, but now accepts an _argument_.
    // before, every foo that fooMaker made said the same thing.
    // now, we can customize this.
    var fooMaker = function( fooCount ){
        var i,
            fooCount = fooCount || 1,
            fooSays = "foo",
            foo = function(){
                // note, we're returning fooSays from the parent scope
                //  (from the current invocation of fooMaker)
                return fooSays; 
            };
        for( i=1; i<fooCount; i++ ){
            // ...and, we're repeating "foo" fooCount times.
            fooSays += " foo";
        }
        // then returning the new foo function as normal.
        return foo;
    };
    
    // your foo function...    // what it will say when invoked
    var foo1 = fooMaker( 1 );  // "foo"
    var foo_ = fooMaker();     // "foo" (note the default "1" in fooMaker)
    var foo5 = fooMaker( 5 );  // "foo foo foo foo foo"
    
    #198289
    __
    Participant

    This reply has been reported for inappropriate content.

    same as last example:

    http://codepen.io/anon/pen/ogQwYa

    #198451
    porgeet
    Participant

    Hey __

    Thanks a lot for that explanation, that really helped :)

    Just to be sure I’m understanding it right:

    var myBalanceMethod = john.askTeller(); assigns the result of the askTeller function for the object john. That result is the function returnBalance.

    Then I have to call the returned function stored in the variable myBalanceMethod (ie. the returnBalance function. The function returnBalance returns the variable bankBalance stored within the object.) and I call it by adding the (); to the end of it. That is then assigned to the variable myBalance

    So console logging myBalance will log the result of the returnBalance funciton, the bankBalance variable of 7500.

    I see it as a sequence of sorts:

    1. Calling askTeller (whose result is another function) and store it in the variable myBalanceMethod
    2. Calling myBalanceMethod (because it’s equal to a function) and store the returned bankBalance value in myBalance
    3. myBalance contains the end result of that sequence the bankBalance variable which is the 7500 number

    I think I may have just written the same thing twice there :P

    If I had more functions accessing other functions that eventually accessed the variable I needed, that process of assigning called functions to variables would just go on and on until I reached the end result of the variable, is that about right?

    Cheers
    porgeet

    #198469
    __
    Participant

    This reply has been reported for inappropriate content.

    pretty much (unless I’m misreading something : ).

    #198481
    porgeet
    Participant

    Sweet, thanks a lot for your help :D

    One last thing :P

    Do I add the (); because it’s equal to a function myBalanceMethod. You don’t usually add the brackets to a variable unless they are equal to a function?

    Thanks again :D
    porgeet

    #198486
    __
    Participant

    This reply has been reported for inappropriate content.

    () invokes the var/property/label. If the {thing-in-question} is a function, then this will work. If not, it will break.

Viewing 9 posts - 1 through 9 (of 9 total)
  • You must be logged in to reply to this topic.
icon-link icon-logo-star icon-search icon-star