I am writing domain objects in Javascript which gets populated with the database fields. Suppose I have two objects dog and cat and I have following constructor function definition:
function Dog(opt_data) {
var data = opt_data || {};
this.createdAt = data['created_at'];
this.updatedAt = data['updated_at'];
this.name = data['name'];
this.breed = data['breed'];
}
function Cat(opt_data) {
var data = opt_data || {};
this.createdAt = data['created_at'];
this.updatedAt = data['updated_at'];
this.name = data['name'];
this.fur = data['fur'];
}
Now, both of the above objects have craetedAt and updatedAt properties. So, should I create a new class BaseModel which has there properties and let all the objects inherit that or is there any better alternative in javascript for this pattern?
Update 1:
My understanding from comments and answer.
function Cat(opt_data) {
var data = opt_data || {};
this.name = data['name'];
this.fur = data['fur'];
this.updateTimestamp(data);
}
Cat.prototype = Object.create({
updateTimestamp: function(data) {
this.createdAt = data['created_at'] || new Date();
this.updatedAt = data['updated_at'] || new Date();
}
});
both of the above objects have craetedAt and updatedAt propertiesnot in the code you posted.