简体   繁体   中英

How can i call a function, whose name is dynamically created by combining some variables in node.js?

I have a constructor in Node.js

    function Response() {
                var numberOfArguments = arguments.length;
                var getArguments = arguments;             
                var newConstructor = arguments.callee.name + i; // ie, (Constructor Name + numberOfArguments)

                /* Here i want to call the constructor with the value in newConstructor and pass the arguments in getArguments*/
               // ie, call function like Response0();
               //                        Response1(getArguments[0]);
    }

    function Response0() {
         //Constructor Body for Response0()
    }

    function Response1(sid) {
          //Constructor Body for Response0()
    }

Now my question is How can i call these functions Response0() or Response1() depending upon the number of arguments that come into the Response constructor .

I didn't tried this but maybe that's one way to go with:

Response0() {
     //Constructor Body for Response0()
}

Response1(sid) {
      //Constructor Body for Response0()
      //NOTE: sid will be an array of length 1
}

//here we create kind of a lookup table that binds constructors to a specific number of arguments
var dictionary = {
    0 : Response0,
    1 : Response1
};

Response() {
           var args = Array.prototype.slice.call(arguments),
               numberOfArguments = args.length;

           if (dictionary.hasOwnProperty(numberOfArguments) {
               //here we call the constructor and give an array of the current args to work with
               new dictionary[numberOfArguments](args);
           }
}

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