2009-07-10 90 views
12

我可以調用的公共方法,從私立學校內:的Javascript調用的公共方法從同一對象內的私人一個

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

回答

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

感謝您的快速回答,我可以把公共變量中的一種以上的方法,我想你的模型,但我有一些sintax錯誤 – krul 2009-07-10 20:32:22

+0

公共僅僅是一個JS對象; – BaroqueBobcat 2009-07-10 20:33:33

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

這種方法不是一個明智的方法嗎?我不知道,雖然

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(); 
相關問題