Simple definition:
- delegate is a value – reference to the pair of object and its method. Lets name them as delegate.object and delegate.method.
- delegate invocation is a way of calling of delegate.method in context of delegate.object. So inside code of the delegate.method variable this points to the delegate.object.
To be practically useful delegate in JavaScript must be implemented as a reference to function so, for example, we can say:
window.setTimeout( delegate( obj, obj.method ), 1000 );
and obj.method will be invoked one second later with this referring to the obj.
Here is probably simplest possible implementation of such delegate function in JavaScript (and in TIScript):
function delegate( that, thatMethod )
{
return function() { return thatMethod.call(that); }
}
It returns reference to the function-thunk ( delegate per se ). This function-thunk being called will invoke thatMethod in context of that object. This implementation employs the fact that namespace of inner function in JS includes namespace of outer function.
Technically this means following: call frames in JS are also (GC-able) objects and body of the function (callee) has access to the frame of caller.