我如何调用一个函数,其名称是通过组合node.js中的一些变量动态创建的?

时间:2016-04-20 05:17:10

标签: javascript angularjs node.js function constructor

我在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()
    }

现在我的问题是我如何调用这些函数Response0()或Response1(),具体取决于进入Response构造函数的参数数量。

1 个答案:

答案 0 :(得分:3)

我没试过这个,但也许这是一种方式:

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);
           }
}