Javascript在同一个对象中从私有方法调用公共方法

时间:2009-07-10 20:15:00

标签: javascript oop

我可以在私人方法中调用公共方法:

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 个答案:

答案 0 :(得分:15)

做类似的事情:

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

答案 1 :(得分:14)

为什么不把它作为你可以实例化的东西呢?

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

答案 2 :(得分:3)

public_method1不是公开方法。它是匿名对象上的一个方法,它完全在构造函数的return语句中构造。

如果你想调用它,为什么不这样构造对象:

var myObject = function() {
    var p...
    function private_method() {
       another_object.public_method1()
    }
    var another_object = { 
        public_method1: function() {
            ....
        }
    }
    return another_object;
}() ;

答案 3 :(得分:2)

这种做法不是明智之举吗?我不确定

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

答案 4 :(得分:0)

不知道直接答案,但以下情况应该有效。

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

  return {
    public_method1: _public_method1
  };
} ();
相关问题