I don’t know if the title for this entry is well chosen, but in short: For a long time I searched for a possibility to create classes I am used to write like in object oriented programming languages. So I asked google about that and discovered I am not alone. But I found nothing that satisfied my needs. Sure, you can create an object using code like that:
var obj1 = function() {};
obj1.prototype = {
foo: "foo-obj"
};
var obj2 = obj1;
obj2.prototype.foo2 = "obj";
obj2.prototype.setFoo = function(val) {this.foo = val;};
But that looks nothing like object oriented code I used to write in other languages. Besides, writing all of this .prototype seems more complicated as it should be. So I looked further. With prototype you can write:
var Animal = Class.create({
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
}, speak: function() {
alert(name + " says: " + sound + "!");
}
});
// subclassing Animal
var Snake = Class.create(Animal, {
initialize: function($super, name) {
$super(name, 'hissssssssss');
}
});
From Prototype documentation
Pretty good so far, but there are still some issues. The greatest issue is, you need prototype to create such classes. For some projects prototype is useful, for small projects it is simply to much. Besides you can’t create classes which inherit from multiple classes, and this $super in that constructor, must I really write that? I mean, within the parameterlist of a function should only be variables, that you expect when calling var snake1 = new Snake("billy the snake");
So I thought about it and a little bit inspired by all I saw I decided what I wanted to write. Code like that:
var ParentClass = new Class.create({
initialize: function(fooval) {this.foo = fooval;}
, foo: ""
, setFoo: function(val) { this.foo = val; }
});
var SubClass = new Class.create({
initialize: function() {this.super("barent");}
, foo2: "barcelona"
}, ParentClass);
So I developed 23 lines that make this possible. Here it is:
var Class = {
create: function() {
var t = function() {if(this.initialize) this.initialize.apply(this, arguments);};
t.prototype.super = function() {
if(typeof this._super != "undefined")
this._super.initialize.apply(this, arguments);
};
t.extend = function() {
for(var i = 0; i < arguments.length; ++i) {
if(typeof arguments[i] == "function")
arguments[i] = new arguments[i]();
for (var property in arguments[i]) {
if(!t.prototype[property])
t.prototype[property] = arguments[i][property];
}
if(typeof t._super == "undefined")
t.prototype._super = arguments[i];
}
};
t.extend.apply(t, arguments);
return t;
}
};
For all, who want some examples what these 23 lines can do, I created a page for this Class-object. If you have feedback and/or more ideas I would like to hear about it.