tags:

views:

410

answers:

4

Can I call public method from within private one:

var myObject = function() {
   var p = 'private var';
   function private_method1() {
      //  can I call public mehtod "public_method1" from this(private_method1) one and if yes HOW?
   }

   return {
      public_method1: function() {
         // do stuff here
      }
   };
} ();
+3  A: 

do something like:

var myObject = function() {
   var p = 'private var';
   function private_method1() {
      public.public_method1()
   }

   var public = {
      public_method1: function() {
         alert('do stuff')
      },
      public_method2: function() {
         private_method1()
      }
   };
   return public;
} ();
//...

myObject.public_method2()
BaroqueBobcat
Thanks for your fast answer, Can I put more than one method within public variable, I tried your model but I have some sintax errors
krul
public is just a js object;
BaroqueBobcat
thanks, but in my code refuse to be treated like one, (I'will have to debug it. Thanks again and thanks to Daniel for explanation
krul
I made it work, thanks again to everybody, I accepted "BaroqueBobCat" mainly because he was the first one, but Daniel's answer was more complete
krul
A: 

Do not know direct answer, but following should work.

var myObject = function() 
{
   var p = 'private var';   
  function private_method1() {
   _public_method1()
  }
  var _public_method1 =  function() {
         // do stuff here
    }

  return {
    public_method1: _public_method1
  };
} ();
Mike Chaliy
+2  A: 

public_method1 is not a public method. It is a method on an anonymous object that is constructed entirely within the return statement of your constructor function.

If you want to call it, why not structure the object like this:

var myObject = function() {
    var p...
    function private_method() {
       another_object.public_method1()
    }
    var another_object = { 
        public_method1: function() {
            ....
        }
    }
    return another_object;
}() ;
Daniel Roseman
+1  A: 

Why not do this as something you can instantiate?

function Whatever()
{
  var p = 'private var';
  var self = this;

  function private_method1()
  {
     // I can read the public method
     self.public_method1();
  }

  this.public_method1 = function()
  {
    // And both test() I can read the private members
    alert( p );
  }

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

var myObject = new Whatever();
myObject.test();
Peter Bailey
thanks Peter, Unfortunately I have now lot of code to rewrite the model that I'm using mostly as namespace.
krul