Last active
January 4, 2016 20:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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