Search code examples
javascriptkineticjspaperjs

What is a proper way to create argument var names in a module for a new Class creation?


In the following code example I want to somehow create a var myThingName via a functions arguments so I can avoid having to build global var names outside of the Module. I have tinkered with window['myvarname'] = "yada"; But that's a global and feels like a complete hack.

In short, I am assuming I need to have a way to make many vars like : myThingName_1 myThingName_2 etc...

Background: I am trying to build a Canvas Element constructor to put any number of individual Canvas elements onto the screen. I am using various libraries like Paper.js Kinetic.js etc. When trying to streamline the production I built a Module wrapper but am now stuck at how to create unique var names for the libraries KLASS constructor for their various implementations of stage or scope.

Perhaps I am doing things totally incorrectly from the start. But at the moment I am stumped as to how this goes about or what the name of the pattern I am looking.

var MagicThingModule = {

    createThing : function(myThingNameAsString){
        var myThingName = myThingNameAsString;
        myThingName = new KLASS.Shape({ // code });
    },

    init : function(myThingNameAsString){
        createThing(myThingNameAsString);
    }
}

MagicThingModule.init("sendNameForThing_1");

Solution

  • How about:

    var MagicThingModule = {
        allMyThings: {},
        createThing : function(myThingNameAsString){
            var myThingName = myThingNameAsString;
            myThingName = new KLASS.Shape({ // code });
            this.allMyThings[myThingNameAsString] = myThingName;
        },
    
        // use me to et your thing back...
        getMyThing: function(myThingName){
            return this.allMyThings[myThingName];
        },
    
        init : function(myThingNameAsString){
             createThing(myThingNameAsString);
        }
    }
    

    and you can later reference it by:

    var myThing = MagicThingModule.getMyThing("sendNameForThing_1");