简体   繁体   中英

Javascript calling public method from private one within same object

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

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM