I prefer the me/that/self method to resolve the binding 'problem' in Javascript. Anytime I declare a 'class' that will have functions that may be passed as parameters (e.g. event handlers). Here's an example of my general setup:
function Person(name)
{
var me = this;
this.name = name;
this.alertName = function()
{
alert(me.name);
};
}
var aPerson = new Person('Paul');
setTimeout(aPerson.alertName, 1000);
This works because I've defined var me = this;
in the 'class' definition. This gets repetitive, so as an exercise, I wanted to abstract this and add the me = this
definition to the prototype of Function
so I don't have to do it manually every time. I hope the way I describe it makes sense. I thought something like this would work:
Function.prototype.me = function()
{
return this;
}
I expected a call to me() anywhere in the Person 'class' would work, but it doesn't. I've tried different ways, for instance by extending Function
with a BaseFunction
class that has the definition, but I can't figure it out and I can't find anything by way of Google or on SO.
Here is a jsFiddle with what I've been playing around with if you're interested:
Thanks,
Paul