How to construct JavaScript object (using 'apply')?

后端 未结 2 649
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 21:37

I\'m looking for a way to construct arbitrary JavaScript objects based on (a) the name of the constructor, and (b) an array containing the arguments. I found this function (

2条回答
  •  再見小時候
    2020-12-06 22:07

    I may end up with this simplified version of Mike's triangle-of-hackery:

    function applyCtor2(ctor, args) {
      switch (args.length) {
        case 0: return new ctor();
        case 1: return new ctor(args[0]);
        case 2: return new ctor(args[0], args[1]);
        // add more cases if you like
      }
      var jsStr = "new ctor(args[0]";
      for (var i=1; i

    I'm not using 'apply' here, but I don't miss it. ;-) Any comments?

提交回复
热议问题