5

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 ?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Rename publicStaticProperty to privateStaticProperty
@MBO So how to maintain the old public static property in this code also ? could you update it to contain both of public static and private static ... sorry, I get lost
Side note : in most cases it's better to define methods on the prototype (i.e. Constructor.prototype.publicMethod = function()...) as it avoids their useless duplication.
@dystroy I cannot access my public_property anymore ? same for private_property accessing inside the class. How in your code may I have non-static public and non-static private properties ?
@dystroy You have a bug, I'll edit your answer to fix it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.