javascript - 使用源对象更新目标对象
问题描述
我的问题是我有一个“产品”类,我用它来创建产品并将它们呈现在我的页面中。这个对象有一个这样的构造函数:constructor(title, price, description, imageUrl, id)
,我有一个函数来更新一个现有的产品,通过“更新产品”页面中的一个表单从请求正文中获取它的新道具——然后是一个 POST 路由,就像这样(使用 express):
exports.postEditProduct = (req, res, next) => {
const prodId = req.body.productId,
updatedTitle = req.body.title,
updatedPrice = req.body.price,
updatedImageUrl = req.body.imageUrl,
updatedDesc = req.body.description;
const product = new Product(
updatedTitle,
updatedPrice,
updatedDesc,
updatedImageUrl,
ObjectID(prodId) // I'm using mongodb!
); //rest of the code is just promise stuff...
现在,每当我手动做某事太多次时,我都会想“如果我有一千个这样的东西会怎样”?如果我的对象有一千个道具要更新怎么办?这就是我要解决的问题!使用我将更新的道具传递给构造函数的变量,const product
而无需命名其中的每一个。另外,我知道定义这样的变量并不酷,我只是在这一点上搞砸了,这不会投入生产。
解决方案
我将介绍用于启动类实例的工厂模式。使用 JavaScript,我们可以自由地使用创建 Product 实例的函数,这些函数依赖于大量不同的参数。
const keys = ['title', 'price', ...]
function createProduct(params) {
const product = new Product()
for (let x in params) {
if(params.hasOwnProperty(x) && keys.includes(x)) {
product['any prefix' + x] = params[x]
}
}
return product
}
推荐阅读
- astronomy - Skyfield 年份超出范围
- php - 检查每个站点的最佳方法,如果它是在线 Laravel
- mysql - 在 SQL 中展开和计数
- hp-uft - 使用 OTA 在 ALM 中删除测试集
- linux - 是否可以在 coreos 上禁用幽灵/熔毁/相关补丁?
- angular - 使用 filter、groupby 和 orderby 映射 json 数组的值
- html - 图像在轮播中拉伸
- linkedin - LinkedIn 分享按钮不分享确切的帖子
- php - 在特定 Woocommerce 产品类别存档页面下添加文本
- javascript - 同构样式加载器,无法读取 null 的属性“应用”