12

Can I call public method from within private one:

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

5 Answers 5

15

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() 
Sign up to request clarification or add additional context in comments.

3 Comments

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
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
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
14

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

1 Comment

thanks Peter, Unfortunately I have now lot of code to rewrite the model that I'm using mostly as namespace.
3

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

Comments

2

Is this approach not a advisable one? I am not sure though

var klass = function(){ var privateMethod = function(){ this.publicMethod1(); }.bind(this); this.publicMethod1 = function(){ console.log("public method called through private method"); } this.publicMethod2 = function(){ privateMethod(); } } var klassObj = new klass(); klassObj.publicMethod2(); 

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.