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

最佳答案

我没有试过,但也许这是一种方法:

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

关于javascript - 我如何调用一个函数,该函数的名称是通过结合node.js中的一些变量来动态创建的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36734427/

10-09 16:11
查看更多