Method binding
Ruby has method objects (Method
and UnboundMethod
) for passing references
to an object’s methods, so you can call a method without having a reference to
the object. JavaScript has functions and treats them as first-class values, so
you can get a reference to a method and call it later:
var rex = new Dog('Rex'); var spk = rex.speak; // a reference, we are not calling the method spk('biscuits'); // -> "MY NAME IS AND I LIKE BISCUITS!"
Where did Rex’s name go? The thing is, we’ve not called spk
through the
object rex
, so this
inside the function no longer refers to the right
thing. jsclass
gives each object a method()
method, that returns a method
by name, bound to its source object. This method is simply a JavaScript
function that you can call on its own and maintain the binding of this
:
var speak = rex.method('speak'); speak('biscuits'); // -> "MY NAME IS REX AND I LIKE BISCUITS!"
You can also do this with class methods, since classes are objects too:
var User = new JS.Class({ extend: { create: function(name) { return new this(name); } }, initialize: function(name) { this.username = name; } }); var u = User.method('create'); u('James') // -> {username: 'James'}