Hello Everyone,

Just had an idea for a possible enhancement to Class.create() that I
wanted to float with y'all.   Here's the preamble:

>From knocking around on mailing lists / IRC etc it seems that by far
the most irritating problem for most new JS library users is the idea
that, in JS, methods of objects have no inherent binding to the object
they are attached to so if you do something like this:

Car = Class.create();
Object.extend(Car.prototype, {
 initialize : function(a) {
   this.a = a;
 },
 showA : function() {
   console.log(this.a);
 }
});

This gives the 'expected' result:

a = new Car(7);
a.showA(); //=> 7

But this doesn't:

func = a.showA
func(); //=> undefined

This is always a problem inside event handlers and the enumerable
functions and of course the way to stop it is to use bind().  But I
think possibly that a point of confusion in Prototype particularly
that if you use Class.create() you expect a thing that acts like a
class which it of course doesn't.  So....

How about this:

Class = {};
Class.create = function() {
 return function() {
   this.initialize.apply(this, arguments);

   for (var prop in this)
     if (typeof this[prop] == 'function')
       this[prop] = this[prop].bind(this);
 };
}

Which also binds methods of the object to the object itself
automatically so you can point event handlers etc straight to methods
of objects and they remain bound....?

Any good?  Any problems Im not thinking of?



-- 
Dan Webb
http://www.danwebb.net

Event Wax (http://www.eventwax.com)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Prototype: Core" group.
To post to this group, send email to prototype-core@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/prototype-core?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to