Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create public and private members?

I'm a bit confused, how can I create public and private members.

My code template so far is like:

(function()){
   var _blah = 1;

   someFunction = function() {
     alert(_blah);
   };

   someOtherFunction = function() {
     someFunction();
   }
}();
like image 308
Blankman Avatar asked May 10 '10 14:05

Blankman


4 Answers

You may want to use the Yahoo Module Pattern:

myModule = function () {

    //"private" variables:
    var myPrivateVar = "I can be accessed only from within myModule."

    //"private" method:
    var myPrivateMethod = function () {
        console.log("I can be accessed only from within myModule");
    }

    return {
        myPublicProperty: "I'm accessible as myModule.myPublicProperty."

        myPublicMethod: function () {
            console.log("I'm accessible as myModule.myPublicMethod.");

            //Within myProject, I can access "private" vars and methods:
            console.log(myPrivateVar);
            console.log(myPrivateMethod());
        }
    };
}();

You define your private members where myPrivateVar and myPrivateMethod are defined, and your public members where myPublicProperty and myPublicMethod are defined.

You can simply access the public methods and properties as follows:

myModule.myPublicMethod();    // Works
myModule.myPublicProperty;    // Works
myModule.myPrivateMethod();   // Doesn't work - private
myModule.myPrivateVar;        // Doesn't work - private
like image 51
Daniel Vassallo Avatar answered Sep 26 '22 08:09

Daniel Vassallo


You don't. You can rely on convention, prepending _ to your private attributes, and then not touching them with code that shouldn't be using it.

Or you can use the function scope to create variables that can't be accessed from outside.

like image 37
Esteban Küber Avatar answered Sep 24 '22 08:09

Esteban Küber


In javascript every object member is public. Most popular way of declaring the private field is to use the underscore sign in it's name, just to make other people aware that this is private field:

a = {}
a._privateStuff = "foo"

The other way to hide the variable is using the scopes in javascript:

function MyFoo {
    var privateVar = 123;
    this.getPrivateVar = function() {
        return privateVar;
    }
}

var foo = new MyFoo();

foo.privateVar // Not available! 
foo.getPrivateVar() // Returns the value

Here's the article that explains this technique in details:

http://javascript.crockford.com/private.html

like image 36
Juriy Avatar answered Sep 24 '22 08:09

Juriy


Three things:

  1. IIFEs:
    It seems like you need to refresh your knowledge regarding this pattern. Have a look at this post before using an IIFE again.

  2. Global public vs. Safe public:
    Skipping var keyword with someFunction and someOtherFunction leads to registration of these function objects in the global scope, i.e., these functions can be called and reassigned from anywhere in the code. That could lead to some serious bugs as the code grows bigger in size. Instead, as Daniel suggested, use the module pattern. Though you can use other methods too like Constructors, Object.create(), etc, but this is pretty straightforward to implement.

    /* create a module which returns an object containing methods to expose. */
     var someModule = (function() {  
         var _blah = 1;  
          return {  
            someFunction: function() {},  
            someOtherFunction: function() {}  
          };  
     })(); 
    /* access someFunction through someModule */
    someModule.someFunction();
    // ...
    // ....
    /* after 500+ lines in this IIFE */
    /* what if this happens */  
    someFunction = function() {  
        console.log("Global variables rock.");  
    };  
    /* Fortunately, this does not interfere with someModule.someFunction */
    
  3. Convention and scope combined:
    We cannot expect from every developer to follow the underscore or the capitalization convention. What if one of them forgets to implement this technique. Instead of just relying upon the convention (_private, GLOBAL) and the scope (function scoping), we can combine both of them. This helps in maintaining consistency in coding style and provides proper member security. So, if next time somebody forgets to capitalize their globals, the console (in strict mode) can prevent the world from ending.

like image 38
Harsh Vardhan Avatar answered Sep 23 '22 08:09

Harsh Vardhan