I have a case where I have an object, "foo", that needs to call a callback on another object, "bar", and I need the context within the callback to be that of "bar". The kicker though, is that beyond getting its callback from "bar", "foo" should not know anyting about it.
Example:
var foo =
{
message: "Hello foo",
doStuff: undefined
};
var bar =
{
message: "Hello bar",
callback = function ()
{
alert(this.message);
}
};
foo.doStuff = bar.callback;
foo.doStuff();
I realize that normally you would use "call" or "apply" to switch the context to bar but in my particular case, at the time of calling foo.doStuff() I no longer have information about where the callback came from. So is there another way of figuring the context (say from within the callback function itself)?
foo.doStuff = bar.callback.bind(bar);. orfoo.doStuff = function () {bar.callback.call(bar)};which is basically whatbindis doing behind the scenes.bar.callback.call(bar)is functionally identical tobar.callback().