【问题标题】:Dynamic instantiations passing parameters动态实例化传递参数
【发布时间】:2017-08-07 20:18:15
【问题描述】:

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

在下面的示例中,我有一个根class Product,它由class FoodclassFurniture 扩展,这些扩展类的参数不同,需要插入到它们的相对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


    【解决方案1】:

    创建一个name -> constructor 映射。 classes 不会成为全局对象的属性:

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

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

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

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

     new cls[item.metaType](item);
    

    【讨论】:

    • 您只需将item 传递给构造函数。
    • 是的,很抱歉一开始没听懂你在说什么……只需使用item在每个类中解构即可
    • 这是你见过的最有效的方法吗?我之前使用过switch 语句,我想如何动态地做到这一点。
    • 我觉得没关系。 switch 当然也可以。我无法想象这部分在您的应用程序中对性能至关重要。
    • 我的意思是说毫秒,但它们加起来有一个巨大的列表,但无论如何都在实施分页,只是一直在努力争取最好的结果,我猜哈哈。
    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多