I have been using the John Resig javascript class implementation in my web apps, but the tests shows it is really slow. I really find it useful for the way of extending objects, and the benefits got from having a better code and less redundancy.
In some post was explained that it was slow because of the how the _super method is handled.
Since super is Java style, and most of time I develop in PHP, I made my own version of Resig implementation using the parent:: style (used in PHP), with the aim to make this faster. Here it is:
(function () {
this.Class = function () {
};
Class.extend = function extend(prop) {
var prototype = new this();
prototype.parent = this.prototype;
for (var name in prop) {
prototype[name] = prop[name];
}
function Class() {
this.construct.apply(this, arguments);
}
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.extend = extend;
return Class;
};
}) ();
Case of use:
var Person = Class.extend({
construct: function (name) {
this.name = name;
},
say: function () {
console.log('I am person: '+this.name);
},
});
var Student = Person.extend({
construct: function (name, mark) {
this.parent.construct.call(this, name);
this.mark = 5;
},
say: function () {
this.parent.say.call(this);
console.log('And a student');
},
getMark: function(){
console.log(this.mark);
}
});
var me = new Student('Alban');
me.say();
me.getMark();
console.log(me instanceof Person);
console.log(me instanceof Student);
Any opinion about this? Is this fast? What about correctness?
Some test shows that is the fastest for the moment.
My next improvement will be to remove the scope .call(this):
this.parent.say.call(this);
to
this.parent.say();