Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static functions in javascript

Tags:

javascript

How can I create a function that can't be called from outside?

var obj = {
    function1: function(){
        alert("function1");
    },
    function2: function(){
        alert("function2...");
        obj.function1();
    }
};
// so how to make this function unaccessible 
obj.function1();
// and you could only call this function
obj.function2();
like image 355
user Avatar asked Jul 10 '10 11:07

user


People also ask

What is a private static function?

A static private method provides a way to hide static code from outside the class. This can be useful if several different methods (static or not) need to use it, i.e. code-reuse.

What is private function in JavaScript?

A private function can only be used inside of it's parent function or module. A public function can be used inside or outside of it. Public functions can call private functions inside them, however, since they typically share the same scope.

Can a static method be private?

Yes, we can have private methods or private static methods in an interface in Java 9.

What are static functions in JavaScript?

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.


1 Answers

You may want to consider using the Yahoo Module Pattern. This is a singleton pattern, and the methods are not really static, but it may be what you are looking for:

var obj = (function () {

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

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

   return {
      myPublicVar: "I'm accessible as obj.myPublicVar",

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

         //Within obj, 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 myPublicVar and myPublicMethod are defined.

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

obj.myPublicMethod();    // Works
obj.myPublicVar;         // Works
obj.myPrivateMethod();   // Doesn't work - private
obj.myPrivateVar;        // Doesn't work - private
like image 194
Daniel Vassallo Avatar answered Oct 18 '22 23:10

Daniel Vassallo