Clayton
Clayton

Reputation: 5350

How to create javascript function lookup object?

I'm attempting to create a function lookup in Javascript essentially mapping a data type to a function that does something for that data type. Right now I have something similar to:

var Namespace = Namespace || {};
Namespace.MyObj = function () {
    var stringFunc = function(someData) {
        //Do some string stuff with someData
    };

    var intFunc = function(someData) {
        //Do some int stuff with someData
    };

    var myLookUp = {
        'string': stringFunc,
        'int' : intFunc
    };

    return {
         PublicMethod: function (dataType, someData) {
             myLookUp[dataType](someData);
         }
    };
} ();

When I invoke Namespace.MyObj.PublicMethod(dataType, someData) I get an error that myLookUp is not defined. I'm assuming I'm not going about setting up the function lookup object correctly, but not sure how to do so. Thanks for any help.

Upvotes: 0

Views: 3914

Answers (2)

Clayton
Clayton

Reputation: 5350

Just looked at my post after I wrote it up, stupid oversight, I'm declaring the properties as strings, instead of just properties.

....
var myLookUp = {
    string: stringFunc,
    int: intFunc
};
....

Fixes the issue.

Some additional follow up, in my actual code dataType is the result of a jQuery select. Don't know why or if this would be browser dependant (I'm using FireFox), but using double quotes around the property definition works, single quotes does not, and no quotes works as well. :-\

Upvotes: 0

Yisroel
Yisroel

Reputation: 8174

The problem might simply be incorrect case

myLookup[dataType](someData);

should be (notice the capital U)

myLookUp[dataType](someData);

Upvotes: 3

Related Questions