bound methods / functions

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

bound methods / functions

Garrett Smith
Why not bind prototype methods?

"Instance methods are functions that are defined without the static
attribute and inside a class definition. Instance methods are
associated with an instance of the class they are defined in. Instance
methods can override or implement inherited class or interface
methods, and always have a value bound to this."

Most classes will want to create a prototype that instances can delegate to.

An example to demonstrate the problem:

Anim = function() {};

Anim.prototype = {
  start : function() {
  // the - this - value is not the current object, but will actually
be the window object.
    setInterval( this.move, 10 ); // error: window.move is undefined.
 ,move : function() { }

The code can be refactored by making the start method an instance
method to achieve the desired result.

It would be more convenient to not require such change.

Binding the object to it's prototype methods would alleviate this burden.

Another possibility would be to have setTimeout be an instance method
of object and execute with the thisArg as the object on which
setTimeout was called. This fix, however won't resolve problem in a
pub-sub event registry, such as YAHOO.util.Event. Peter Micheaux
brought this up and Brendan's comment "lots of Ajax libraries
implement it much as you show  below. The ones I've looked at play
their own custom variations on a  theme, so wouldn't all be subsumed
by a standard."

Binding prototype methods would make it easier to resolve scope, so
these libraries wouldn't have all their "unique" designs. It would be
possible to creatively bound prototype methods in ES4.

 * pro: behavior would be consistent with instance methods.
 * pro: would alleviate the burden of refactoring prototype to
instance methods when users of a class need bound methods.
 * con: Prototype methods are currently not bound, so thisArg resolves
to the global object.

Are there any other cons (for binding prototype methods)?

How severe is breaking the thisArg in prototype methods < ES4 ?

What other options are available? Partial apply?


Programming is a collaborative art.
Es4-discuss mailing list
[hidden email]