Re: Re: Prototype OOP example

Cliff Mees
Tue, 27 Dec 2005 03:19:46 -0000

Victor,

Thanks for putting that clearer (and more correctly) than I did!

Object#extend does return the extended object, but also affects the
first parameter ("destination") in-place, extending it without
requiring the return.

My initial example actually re-defined the base class in terms of the
inherited class (i.e. Labour and Worker had the same definitions --
oops!).

I take it that the return from Object#extend is provided to allow
things like:

Object.extend(base_obj, {newMethod: function() { // do
something }}).newMethod();


Cheers,

Cliff

On Dec 26, 2005, at 15:56, Victor Borja wrote:

> 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