Search code examples
javascriptclassinstanceinstance-variablesclass-variables

What is the Javascript equivalent of a Class variable?


Edit: Thanks @Aadit M Shah for confirming.

function Apple () {}
Apple.someVar = null; // Class variable
Apple.prototype.someVar = null; // Instance variable

Solution

  • JavaScript is a functional language and features of classical programming languages are not directly supported but can be achieved by the concept of closures.

    In the code snippet you gave, both Apple.someVar and Apple.prototype.someVar will have the same value for all objects created from the Apple constructor function, i.e. like a class variable.

    To achieve the functionality of instance variables, use closures. You can look online for more help on closures, here's reference http://javascript.crockford.com/private.html

    I am providing a small code snippet to to make it clear.

    function Apple(property){
      var color = property.color; //instance variable
      this.getColor = function(){
        return color;
     };  
    }
    Apple.type = "fruit"; //class variable
    
    var redApple = new Apple({color:'red'});
    var greenApple = new Apple({color:'green'});  
    

    both the variables redApple and greenApple share the same property 'type' but each has its own color property.