pav
5/21/2013 - 8:33 PM

Read over the code carefully and you will notice that in the giggles function we are calling the function giggle. However we call giggle usi

Read over the code carefully and you will notice that in the giggles function we are calling the function giggle. However we call giggle using the syntax this.giggle() instead of person.giggle(). It is important to note that this refers to the object which contains the function. Thus it can only be used from within an object. For this reason when you call a function within an object from outside of that object always use ObjectName.FunctionName.

The syntax person.giggle() would have worked in this circumstance but it is considered less error prone and better stylistically to use this. A good rule of thumb is if you are not within an object use ObjectName. If you are within an object and want to use a function or variable contained within that object use this.

// Here is our person object
    var person = {
        //giggle
        //returns: 'giggle'
        giggle: function(){
            return "giggle";
        },
        //giggles
        //parameters: n - number of giggles
        //returns: string of giggles of n giggles long
        giggles: function(n){
            if (n>1)
                return this.giggle() + " " + this.giggles(n-1);
            if (n===1)
                return this.giggle();
        },
            
        fiveGiggles: function(){
            return this.giggles(5);
        }

    };
   // console.log(person.giggle());
    console.log(person.fiveGiggles(5));