【发布时间】:2018-03-09 17:37:15
【问题描述】:
我基本上正在尝试为一个小项目编写一个自定义 ORM,并且我正在使用一个类来设置我的记录,默认情况下,所有记录都将通过一种类型检查器,该类型检查器将根据我的内容转换任何值说他们应该是
export default class Record {
constructor(...props) {
const [model, data] = props;
forOwn(data, (value, key) => {
if (model.hasOwnProperty(key)) {
this[key] = attr(model[key], value);
} else {
this[key] = value;
}
});
}
}
通过循环数据数组并从中创建新实例就可以正常工作
data.forEach((item) => {
serializedData.push(new Item(model, item));
});
Item 只是一个简单的扩展类
class Item extends Record {
constructor(...props) { super(...props); }
}
这是我遇到问题的地方,我想向Item 子类添加一个新的itemImage 属性,该子类将采用一些现有值并从中创建一个URL。
这两种方法我都试过了,我在网上搜索后发现的,但都不起作用
Reflect.defineProperty(Item.prototype, 'itemImage', {
get() {
return `//res.cloudinary.com/***/image/upload/${this.image.image_crop}/${this.image.image_version}/${this.auction_code}/${this.image.original_image_name}`;
}
});
和
class Item extends Record {
...
get itemImage() {
return this.getItemImage();
}
getItemImage() {
return `//res.cloudinary.com/***/image/upload/${this.image.image_crop}/${this.image.image_version}/${this.auction_code}/${this.image.original_image_name}`;
}
}
我该怎么做呢?
编辑
attr 的作用如下
const attr = (type, data) => {
switch (type) {
case 'number':
return parseFloat(data);
case 'string':
return data.toString();
case 'object':
if (typeof data === 'string' && data.indexOf('{') > -1) {
return JSON.parse(data);
} else {
return data;
}
}
};
这是一个完整的沙盒,带有反应演示
【问题讨论】:
-
与您的问题无关,但仅供参考,您应该使用
Object.defineProperty而不是Reflect.defineProperty,否则如果设置属性失败,您可能会默默吞下错误。 -
attr()在做什么? -
你能创建一个 jsfiddle 吗?
-
@JonasW。添加了
attr()函数引用。 @JoeWarner 添加了一个 jsfiddle 链接
标签: javascript ecmascript-6 es6-class