【发布时间】:2017-08-07 20:18:15
【问题描述】:
我遇到了从不同类动态生成对象实例的问题。所以我有一个服务器响应返回一个产品数组,这些产品的类型不同,这将根据要使用的实例化类以及传递给构造函数的参数而有所不同。
在下面的示例中,我有一个根class Product,它由class Food 和classFurniture 扩展,这些扩展类的参数不同,需要插入到它们的相对constructors() 中。
我正在使用产品属性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]());
});
})();
问题:如何动态实例化不同的类并传递参数?
【问题讨论】:
标签: javascript ecmascript-6 es6-class