1

I have read in a post JavaScript private methods that we can "simulate" private method in javascript.

function Restaurant(price)
{
    var myPrivateVar;

    this.price = price;

    var private_stuff = function()   // Only visible inside Restaurant()
    {
        myPrivateVar = "I can set this here!";
    }

   this.toto = function() {

       private_stuff();
       // do sthg 
   }
}

When I try to call price member in private_stuff method, it doesn't work :

 var private_stuff = function()   // Only visible inside Restaurant()
        {
            myPrivateVar = "I can set this here!";
            alert(this.price); // return undefined !
        }

So how to use public properties in a private method in javascript ?

Community
  • 1
  • 1
scanpat
  • 309
  • 1
  • 4
  • 8
  • 2
    What you wrote it doesn't really makes sense; you should at least give the complete picture: _where_, and _how_, you call `private_stuff`? – ZER0 Oct 19 '13 at 10:31
  • i want to call private_stuff in a public method like "toto" – scanpat Oct 19 '13 at 10:53
  • Take a look to my answer here: http://stackoverflow.com/questions/19419897/making-javascript-private-methods-accessible-to-its-public-methods/19420598#19420598 – ZER0 Oct 19 '13 at 15:01

2 Answers2

0

The problem is: this, inside the private_stuff function, refers to itself, not to the object constructed by Restaurant constructor. There are several ways of binding the method to the object, one simple way to do is:

this.toto = function() {

   private_stuff.call(this);
   // do sthg 

}

That invokes the function in the context of your object.

ejosafat
  • 401
  • 2
  • 12
-1

I've found the solution : remove "this."

scanpat
  • 309
  • 1
  • 4
  • 8
  • It's actually not "the" solution: first of all, you won't be able to access from a public method to `private_stuff`. If somehow you will handle to access to `private_stuff`, then without `this` your function will considered only the `price` when the instance was created. Any further change won't be took in account. – ZER0 Oct 19 '13 at 15:04