Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:

(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();

Update 1: For some strange unexplained (but explained) reasons this test is not working any more, raising a too much recrusion error (but it worked some days ago!!!!)

I updated the test and fix the issue with this test. This is leading to strange results. On Chrome 39 it reports to be the fast class definition, on Firefox 35 it seems to be slow.

share|improve this question
    
Welcome to Code Review! This looks like a pretty good first question, so I'm sure you'll soon get useful reviews. –  Edward Jan 15 at 12:22
    
Thank you. I posted it first on stackoverflow, but in this years the stack sites have been really grow and specialized –  albanx Jan 15 at 12:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.