简体   繁体   中英

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.

The problem might simply be incorrect case

myLookup[dataType](someData);

should be (notice the capital U)

myLookUp[dataType](someData);

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. :-\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM