Search code examples
javascriptjqueryprototypejs

I need data in a class - how can I get that data without creating a new class?


lets say I have a class like so.

var foodData = Class.create({
initialize: function() {
    this.foodType = {
        "grains" : {
            "item1" : "20",
            "item2" : "60"                   
        },             
         "liquod" : {
            "item1" : "30",
            "item2" : "90"                   
        },
_someMethod: function(){

}

});

In reality, the class is rather large with alot of methods. I ONLY want to access the data in the hash "foodtype". Is there a way I can go in and get that without creating a new class and reading in that way.. ala

var newSomething = new foodData;
    newSomething.foodType;

Solution

  • Yeah, your access should look like this:

    var newSomething = new foodData();
    newSomething.foodType;
    

    You just need the constructor called is all.

    But it would be better to create a getter for it, like this:

    var foodData = Class.create({
      initialize: function() {
        var foodType = {
            "grains" : {
                "item1" : "20",
                "item2" : "60"                   
            },             
            "liquod" : {
                "item1" : "30",
                "item2" : "90"                   
            }
         };
    
         this.getFoodType = function() {
             return foodType;
         };
      },
      _someMethod: function(){
    
        }
    });
    

    That way you can prevent someone from changing it. (Although you should return a CLONE of the foodType, but this should get the point accross to the end user).

    If you are having memory concerns because of the size of the data in foodType, then you can try this method that creates a static variable foodType.

    var FoodData = (function() {
        var foodType = {
            "grains" : {
                "item1" : "20",
                "item2" : "60"                   
            },             
            "liquod" : {
                "item1" : "30",
                "item2" : "90"
            }
         };
    
        return new Class.create({
             initialize : function() {
             },
             getFoodType : function() {
                 return foodType;
             },
             _doSomething : function() {
             }
         });
    })();
    

    Now no matter how many FoodData classes you create, they will each share the same data.

    var newSomething = new FoodData();
    var anotherSomething = new FoodData();
    

    newSomething.getFoodType() is the same as anotherSomething.getFoodType()

    newSomething.doSomethingToData();
    

    newSomething.getFoodType() is still the same as anotherSomething.getFoodType()