传递参数

时间:2017-08-07 20:18:15

标签: javascript ecmascript-6 es6-class

我遇到了动态生成不同类的对象实例的问题。所以我有一个服务器响应返回一个产品数组,这些产品的类型各不相同,因为要使用的实例化类以及传递给构造函数的参数会有所不同。

在下面的示例中,我有一个class Productclass Food扩展了classFurnitureconstructors()这些扩展类的参数不同,需要在相对product.metaType中插入。

我正在使用产品属性class来保存有关//root product class which all inherit from class Product{ constructor(price){ this.price = price; this.quantity = null; } } //food product class class Food extends Product{ constructor(price,exp){ super(price); this.expiration = exp; } } //furniture product class class Furniture extends Product{ constructor(price,dimensions){ this.price = price; this.dimensions = dimensions; } } class Chair extends Furniture{ constructor(price,dimensions,type){ super(price,dimensions); this.type = type; } } class Pizza extends Food{ constructor(price,exp,type){ super(price,exp); this.type = type; } } class Cookies extends Food{ constructor(price,exp,type){ super(price,exp); this.type = type; } } class IceCream extends Food{ constructor(price,exp,type){ super(price,exp); this.type = type; } } //init (iife) (()=>{ //list of products emulated from a server response var products:[ { metaType: "Pizza", name: "digiorno", price: 20, type: "pepperoni", exp: new Date() }, { metaType: "Chair", name: "Lazy Boy", price: 400, dimensions:{ height: 4, width: 2, length: 6 }, type: "modern" }, { metaType: "Cookies", name: "Mrs. Fields", price: 10, type: "chocolate chip", exp: new Date() }, { metaType: "IceCream", name: "Ben & Jerry's", price: 15, type: "half baked", exp: new Date() } ]; var storeProducts = []; //loop through products array products.forEach((item)=>{ //create new instance of the specific product, append to the 'storeProducts' array //each product contains a metaType property which is the CLASS to use //how can I dynamically do this? storeProducts.push(new window[item.metaType]()); }); })();在实例化中使用的信息。

uploadInfoTemplate = new InfoTemplate ({
    title: "",
    content: "<strong>Segment:</strong> ${segment}" +
             "<hr/>" +
             "<strong>Time:</strong> <i>${dateTime}</i>" +
             "<div style='width: 100%; text-align:right;'>" +
                 "<input class='zoomButton' type='button' value='Zoom to' />" +
             "</div>"
});

问题:如何动态实例化不同的类并传递参数?

1 个答案:

答案 0 :(得分:0)

创建name -> constructor地图。 class es不会成为全局对象的属性:

const cls = {Food, Furniture, ...};

使构造函数接受单个参数并对其进行解构,例如

class Food extends Product{
  constructor({price,exp}){
      //      ^         ^    destructuring
      super(price);
      this.expiration = exp;
  } 
}

然后你可以将整个对象传递给构造函数:

 new cls[item.metaType](item);