Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript calling public method from private one within same object

Tags:

javascript

oop

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
      }
   };
} ();
like image 553
krul Avatar asked Jul 10 '09 20:07

krul


People also ask

Can we call public method from private method?

If a private method must call a public method, then the content of the public method should be taken and placed in a private method, which both methods can then call.

How to make function private in JavaScript?

To make a public method private, you prefix its name with a hash # . JavaScript allows you to define private methods for instance methods, static methods, and getter/setters. The following shows the syntax of defining a private instance method: class MyClass { #privateMethod() { //... } }

What is private in JavaScript?

Private fields include private instance fields and private static fields. Private fields are accessible on the class constructor from inside the class declaration itself. They are used for declaration of field names as well as for accessing a field's value.


2 Answers

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()
like image 127
BaroqueBobcat Avatar answered Sep 22 '22 04:09

BaroqueBobcat


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();
like image 27
Peter Bailey Avatar answered Sep 21 '22 04:09

Peter Bailey