views:

152

answers:

1

Is there a way to call "public" javascript functions from "private" ones within a class?

Check out the class below:

function Class()
{
    this.publicMethod = function()
    {
        alert("hello");
    }

    privateMethod = function()
    {
        publicMethod();
    }

    this.test = function()
    {
        privateMethod();
    }
}

Here is the code I run:

var class = new Class();
class.test();

Firebug gives this error:

publicMethod is not defined: [Break on this error] publicMethod();

Is there some other way to call publicMethod() within privateMethod() without accessing the global class variable [i.e. class.publicMethod()]?

+3  A: 

You can save off a variable in the scope of the constructor to hold a reference to this.

Please Note: In your example, you left out var before privateMethod = function() making that privateMethod global. I have updated the solution here:

function Class()
{
  // store this for later.
  var self = this;
  this.publicMethod = function()
  {
    alert("hello");
  }

  var privateMethod = function()
  {
    // call the method on the version we saved in the constructor
    self.publicMethod();
  }

  this.test = function()
  {
    privateMethod();
  }
}
gnarf