【发布时间】:2016-09-10 01:08:30
【问题描述】:
我有两个这样的对象原型:
function Tag(name, description) {
this.name = name;
this.description = description || null;
}
function Category(name, description) {
this.name = name;
this.description = description || null;
}
两者一模一样,看起来很别扭。是否可以将它们合并到一个名为“Entity”的对象中,并用不同的名称(原始的“Tag”和“Category”)引用它们?
这可能会因为我需要在原型中引用当前原型名称而变得更加复杂。
Tag.prototype.toJSON = function() {
return {
__type: 'Tag',
name: this.name,
description: this.description
};
};
如何将相同的“toJSON”扩展应用到“Entity”对象,但确保它在“__type”字段中返回“Tag”或“Category”,具体取决于所使用的对象?
【问题讨论】:
-
我不会打扰。您的代码更清晰。
-
公平的答案!那我就坚持下去。我总是很想知道是否有更好的方法!
标签: javascript json oop object inheritance