Mansfield
Mansfield

Reputation: 15150

Call this (public) function inside private function

I have the following javascript: (JSFiddle)

$(function () {
    function Cat()
    {  
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();    
        }

        var MakeNoise = function () {
            Meow("noise");
            //Cat.Meow("noise");
            //self.Meow("noise");
            //this.Meow("noise");                      
        }        
    }

    var c = new Cat();
    c.Kick();
});​

When I call the Kick function, I get the error "Meow is not defined" (with any of the four things I tried in the MakeNoise function).

I also tried prototyping like so but that gave me the same error:

Cat.prototype.Meow = function (sound) {
    return this.Meow(sound);    
}

I've sure this has a terribly straightforward solution, but I can't figure out how to successfully call the Meow function of the "Cat" class. How can I do this?

As an aside, does this architecture make any sense at all? My intention was to have Kick and Meow as public functions, and MakeNoise as private.

Upvotes: 0

Views: 173

Answers (1)

Musa
Musa

Reputation: 97672

Save a reference object so you can use it in the MakeNoise function.

$(function () {
    function Cat()
    {  
        var self = this;
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();    
        }

        var MakeNoise = function () {
            //Meow("noise");
            //Cat.Meow("noise");
            self.Meow("noise");
            //this.Meow("noise");                      
        }        
    }

    var c = new Cat();
    c.Kick();
});​

http://jsfiddle.net/mowglisanu/7XEYD/3/

Upvotes: 4

Related Questions