Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create private static function in Javascript?

Tags:

javascript

oop

I'm using the following code to create: private property, private method, public property, public method and public static property.

function ClassA() {

    var privateProperty = 'private_default_value';

    var privateMethod = function() {
        console.log("private method executed ...");
    };

    this.publicProperty = 'public_default_value'; 

    this.publicMethod = function() {
        console.log("public method executed ...");
    };

    ClassA.publicStaticProperty = "public_static_default_value";

    // How to create here: ClassA.privateStaticProperty ?

};

var instance = new ClassA();
instance.publicMethod();
console.log(ClassA.publicStaticProperty);

How can I create a private static property in this class ?

like image 790
Ashraf Bashir Avatar asked Mar 19 '23 04:03

Ashraf Bashir


1 Answers

Here's a solution using an IIFE to create a scope visible by the the constructor ClassA :

var ClassA = (function(){

    var Constructor = function(){
        var privateProperty = "private_default_value";

        var privateMethod = function() {
            console.log("private method executed ...");
        };

        this.publicProperty = "public_default_value"; 

        this.publicMethod = function() {
            console.log("public method executed ...");
        };
    }
    Constructor.publicStaticProperty = 'public_static_default_value';
    var privateStaticProperty = "private_static_default_value";

    return Constructor;
})();

privateStaticProperty is "static" : there's only one property.

privateStaticProperty is "private" : you can't read it from outside the IIFE.

like image 188
Denys Séguret Avatar answered Mar 29 '23 10:03

Denys Séguret