Dynamic instantiation in JavaScript

前端 未结 3 997
情歌与酒
情歌与酒 2020-12-15 22:54

Apart from eval, is there any other way to instantiate an object using variable argument list?

E.g.: var foo = instantiate(className, [arg1, arg2, ...])

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 23:38

    Well you can always do as follows. Anything added to Dino prototype can be shared among the instantiated objects The difference from normal constructor pattern is, the instantiated objects do not have to have the exact same private properties set. They can be set dynamically for each one of them.

    function Dino(a,b){
      for(i = 0; i< a.length; i++) this[a[i]] = b[i];
    }
    
    var props = ["foo", "bar"],
       values = [42, 37],
          obj = new Dino(props,values);
    console.log(obj);

提交回复
热议问题