Skip to content

Instantly share code, notes, and snippets.

@reimund
Last active January 4, 2016 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reimund/8677427 to your computer and use it in GitHub Desktop.
Save reimund/8677427 to your computer and use it in GitHub Desktop.
Model base class. Features inheritance, automatically created accessors (get + set) and encapsulation of data. Setters are chainable.
var Model = function(attrs)
{
this.attrs = attrs;
for (var attr in attrs)
var tmp = function(name) {
this[attr] = function(x) {
if (arguments.length) {
this.attrs[name] = x;
return this;
}
return this.attrs[name];
}.bind(this);
}.bind(this)(attr);
};
Model.extend = function(extras, model)
{
if (2 > arguments.length)
model = Model;
var obj = function(attrs) {
model.call(this, attrs);
if (extras && extras.initialize)
extras.initialize.call(this, attrs);
};
obj.prototype = Object.create(model.prototype);
return obj;
}
var Car = Model.extend({
initialize: function(attrs) {
this.wheels = 'fast';
}
});
var FastCar = Model.extend({}, Car);
var myCar = new Car({ color: 'blue', year: 1999, make: 'Skoda' });
var myFastCar = new FastCar({ color: 'baby-blue', year: 1969, make: 'Fiat' });
console.log('myCar before upgrade: ', myCar.color(), myCar.make() , myCar.year());
// Upgrade!
myCar
.year(2009)
.color('yellow')
.make('Ferrari');
console.log('myCar after upgrade: ', myCar.color(), myCar.make() , myCar.year());
console.log('fastCar: ', myFastCar.color(), myFastCar.make(), myFastCar.year(), myFastCar.wheels);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment