I've created a simple Javascript library to be able to create "classes" and extend them defining instance and static methods and variables.
It consists in a simple function Class with two methods: create and extend.
var Class = function(){};
Class.extend = function(obj){
var Extended = function(){};
for(var key in this.prototype){
Extended.prototype[key] = this.prototype[key];
}
for(var key in obj){
Extended.prototype[key] = obj[key];
};
Extended.prototype.constructor = Extended;
for (var key in this) {
Extended[key] = this[key];
};
return Extended;
};
Class.create = function(constructor){
var created = new this();
for(var key in constructor){
created[key] = constructor[key];
}
return created;
};
Here there's an example of what the library is able to do:
var Model = Class.extend({
fields: {},
save: function(){
return "saving a model at " + Model.url;
},
destroy: function(){
return "destroying...";
}
});
Model.url = "http://localhost";
Model.all = function(){
return "all from " + Model.url;
};
Model.find = function(id){
return "finding by " + id;
};
var User = Model.extend({
fields: {
username: "default username",
password: "default password",
},
logout: function(){
return "logged out " + this.fields.username;
},
destroy: function(){
return this.logout() + " and account destroyed!";
}
});
User.url = Model.url + "/users";
User.all = function(){
return "overriding parent! all from " + User.url;
}
User.findByUsername = function(username){
return "finding by username: " + username;
};
And I've created a js fiddle to test the example http://jsfiddle.net/R6jGe/
There's no way to call a parent instance method or variable.
how do you think the library could be improved?