Re: Prototype OOP example

Victor Borja
Mon, 26 Dec 2005 20:56:25 -0000

QnA wrote:
> Thank you for your example. It is a bit disappointed to me that it is not
> possible to call the superclass''s constructor in prototype.

There''s no such thing as a REAL class in JavaScript (in the sense of
classes as in java, ruby, etc), you have objects (wich have properties)
and functions (wich are objects).

In JS you get only _Initializer Functions_, and fake class inheritance by
calling another initializer within your _subclass_.
Checkout http://javascript-reference.info/#oop

/* Labour is just a _Constructor Function_.
   Prototype''s Class.create just returns a new function that calls
   this.initialize to follow the ruby OO tradition */
Labour = Class.create();
Labour.prototype = {
    initialize: function(name) {
        this.name = name;
    },

    showYourName: function() {
        alert(this.name);
    }
}

/* Worker will be a subclass of Labour */
Worker = Class.create();
/* Thanks to Prototype''s Object.extend you can copy all properties from
   an object to another, we are using this to get all the Labour
   functions in Worker, just as if we had inheritance */
Object.extend(Worker.prototype, Labour.prototype);
/* Next extend our _subclass_, note that we are not using something like:
      Worker.prototype = {  // bla bla }
   Because we would be throwing away all the Labour.prototype properties,
   Instead we just use Object.extend again.
 */
Object.extend(Worker.prototype, {

    /* define our _subclass_ initializer, this overrides the old
       Labour#initialize.
       We could as well, backup the old initializer. I named it _super_
       but it could be whatever you like.
    */
    super: Labour.prototype.initialize,

    initialize: function(name, position) {
      // Calling the _superclass_ initializer
      super.call(this, name);
      this.position = position;
    },

    showYourPosition: function() {
      alert(this.position);
    },

});

Regards,
--
vic