从javascript类中的"私有"方法访问"公共"方法

mon*_*oos 12 javascript oop private public

有没有办法从类中的"私有"函数调用"公共"javascript函数?

看看下面的课程:

function Class()
{
    this.publicMethod = function()
    {
        alert("hello");
    }

    privateMethod = function()
    {
        publicMethod();
    }

    this.test = function()
    {
        privateMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我运行的代码:

var class = new Class();
class.test();
Run Code Online (Sandbox Code Playgroud)

Firebug给出了这个错误:

publicMethod未定义:[中断此错误] publicMethod();

是否有其他方法可以在privateMethod()中调用publicMethod()而无需访问全局类变量[即class.publicMethod()]?

gna*_*arf 8

您可以保存构造函数范围内的变量以保存对其的引用this.

请注意:在您的示例中,您varprivateMethod = function()创建privateMethod全局之前就遗漏了.我在这里更新了解决方案:

function Class()
{
  // store this for later.
  var self = this;
  this.publicMethod = function()
  {
    alert("hello");
  }

  var privateMethod = function()
  {
    // call the method on the version we saved in the constructor
    self.publicMethod();
  }

  this.test = function()
  {
    privateMethod();
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

接受的答案具有的单独副本的可能不希望的副作用publicMethod,testprivateMethod将在每个实例中创建的.避免这种情况的成语是:

function Class()
{}

Class.prototype=(function()
{
    var privateMethod = function(self)
    {
        self.publicMethod();
    }


    return 
    {
        publicMethod: function()
        {
            alert("hello");
        },
        test: function()
        {
            privateMethod(this);
        }
    };
}());
Run Code Online (Sandbox Code Playgroud)

换句话说,您需要this将私有函数作为参数传递.作为回报,您将获得一个真正的原型,而不必使用自己的私有和公共函数版本污染每个实例.

  • 太好了!而不是传入,你也可以总是`privateMethod.call(this)` (2认同)