How to access static properties in an object in JavaScript

1 Answer

0 votes
class Configuration {
    // Define a static property (shared across the entire class)
    static environment = "production";

    // A static method to safely access the static property
    static getEnvironment() {
        // Use the class name or 'this' inside static methods to access static members
        return Configuration.environment;
    }

    // A static method to modify the static property with validation
    static setEnvironment(newEnv) {
        if (typeof newEnv === "string" && newEnv.trim() !== "") {
            Configuration.environment = newEnv;
        }
    }
}

// --- Example Usage ---

// 1. Accessing the static property/method directly via the Class Name (Best Practice)
console.log(`Current Environment: ${Configuration.getEnvironment()}`);

// 2. Modifying the static property via a static setter function
Configuration.setEnvironment("staging");
console.log(`Updated Environment: ${Configuration.getEnvironment()}`);

// 3. Direct access (if the static property is public)
console.log(`Direct Property Access: ${Configuration.environment}`);


/* 
 * Note on Instances:
 * const configInstance = new Configuration();
 * console.log(configInstance.environment); // undefined! 
 * Instances cannot access static properties directly.
 */


/*
run:

Current Environment: production
Updated Environment: staging
Direct Property Access: staging

*/

 



answered 6 days ago by avibootz
...