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();
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.
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.
Yes, we can have private methods or private static methods in an interface in Java 9.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With