Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a static variable inside a JS class

I'm building a static class to store data inside an a array and i want to declare a static variable but i don't know how to do it on javascript.

JS code:

class GCache {

    // Define cache variable
    static cache = {}; // <--- that is what i don't know how to do

    /**
     * Check if data is on cache
     * @param {*} id 
     */
    static isOnCache(id){
        return this.cache.hasOwnProperty(id);
    }

    /**
     * Add data to cache
     * @param {*} id 
     * @param {*} json 
     */
    static addToCache(id, json){
        if(this.isOnCache(id)) return;
        this.cache[id] = json;
    }

    /**
     * Obtain data from cache
     * @param {*} id 
     */
    static getFromCache(id){
        if(this.isOnCache(id)) return;
        return this.cache[id];
    }

}

Thank you <3

like image 613
Nurio Fernández Avatar asked Jan 05 '19 01:01

Nurio Fernández


People also ask

How do you define a variable inside a class in JavaScript?

Use the reserved keyword var to declare a variable in JavaScript. Syntax: var ; var = ; A variable must have a unique name.

How do you declare a static variable inside a method in Java?

Declaration Scope of the Static Variables in Java We cannot declare static variables in the main method or any kind of method of the class. static variables must be declared like a class member in the class.

How do you declare a static variable?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Can a class be static in JavaScript?

Definition and UsageThe static keyword defines static methods for classes. Static methods are called directly on the class ( Car from the example above) - without creating an instance/object ( mycar ) of the class.


1 Answers

In up-to-date JavaScript environments, you can use the static keyword when inside a class to assign properties to the instance itself - the code in your question works fine now.

class SomeClass {
    static someStaticProperty = {}
}
console.log(SomeClass.someStaticProperty);

In older environments, and at the time the question was originally posted, non-function properties couldn't be added to a class itself inside the class definition. It looks ugly, but you'll have to assign the property outside of the class definition:

class GCache {
  ...
}
GCache.cache = {};

Also note that your getFromCache function probably has a bug: you probably want to return early if the id being searched for does not exist in the cache:

if(!this.isOnCache(id)) return;

class GCache {
    /**
     * Check if data is on cache
     * @param {*} id 
     */
    static isOnCache(id){
        return this.cache.hasOwnProperty(id);
    }

    /**
     * Add data to cache
     * @param {*} id 
     * @param {*} json 
     */
    static addToCache(id, json){
        if(this.isOnCache(id)) return;
        this.cache[id] = json;
    }

    /**
     * Obtain data from cache
     * @param {*} id 
     */
    static getFromCache(id){
        if(!this.isOnCache(id)) return;
        return this.cache[id];
    }

}
GCache.cache = {};
GCache.addToCache('myid', 'data');
console.log(GCache.getFromCache('myid'));

But, in this case, it would probably be easier to use a plain object, rather than a class. The class isn't being used to instantiate anything, after all, and with an object, you can both define cache inside the object, and reduce the syntax noise by getting rid of all the statics:

const GCache = {
  cache: {},
  isOnCache(id) {
    return this.cache.hasOwnProperty(id);
  },
  addToCache(id, json) {
    if (this.isOnCache(id)) return;
    this.cache[id] = json;
  },
  getFromCache(id) {
    if (!this.isOnCache(id)) return;
    return this.cache[id];
  }
}
GCache.addToCache('myid', 'data');
console.log(GCache.getFromCache('myid'));

There is currently a proposal allowing you to set static non-method properties onto a class. It's currently at Stage 2, which means it's expected to eventually be implemented officially. Once it lands, the code:

class GCache {
  ...
}
GCache.cache = {};

can be replaced by:

class GCache {
  static cache = {};
  ...
}
like image 136
CertainPerformance Avatar answered Sep 30 '22 11:09

CertainPerformance