Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
   }
}();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
338 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...