2009-07-10 5 views

Répondre

15

faire quelque chose comme:

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

Merci pour votre réponse rapide, je peux mettre plus d'une méthode au sein variable publique, j'ai essayé votre modèle mais j'ai quelques erreurs de SINTAX – krul

+0

public est juste un objet js; – BaroqueBobcat

+0

merci, mais dans mon code refuser d'être traité comme un, (je vais devoir le déboguer Merci encore et merci à Daniel pour explication – krul

0

Je ne sais pas de réponse directe, mais après devrait travail.

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 n'est pas une méthode publique. C'est une méthode sur un objet anonyme qui est entièrement construite dans l'instruction return de votre fonction constructeur.

Si vous voulez l'appeler, pourquoi ne pas structurer l'objet comme celui-ci:

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

Pourquoi ne pas faire cela comme quelque chose que vous pouvez instancier?

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

merci Peter, Malheureusement, j'ai maintenant beaucoup de code pour réécrire le modèle que j'utilise principalement en tant qu'espace – krul

+0

Great! It works! –

2

Cette approche n'est-elle pas recommandée? Je ne suis pas sûr cependant

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