It isn't possible to determine if a call is the last instance in a chain when determining the return value, and here is why:
var result = $("#someDiv").myPlugin.foo().bar()._foo()._bar();
foo returns myPlugin on which bar is called which returns myPlugin on which _foo is called which returns myPlugin on which _bar is called.
So effectively, when _foo returns its value (myPlugin), it is before that value is utilized. Unless _foo is psychic, it can't know what will happen next.
As pointed out in your comments, your best bet is to have some "end" method, like results().
Another suggestion would be to pass a handler in to myPlugin that gets called to set the value using setTimeout(..., 0). Have a value in myPlugin that foo, bar, _foo, and _bar all set. Let's call it returnValue. Modify myPlugin to accept a method as it's only parameter. Let's call that handler. This method's first argument will contain the value. Inside of myPlugin, before your return, do:
window.setTimeout(function () {
handler(returnValue);
}, 0);
Since setTimeout's function parameter will not be called until execution is finished, it will contain the last value set for returnValue - effectively the value set by the last call in the chain. I'd consider this the closest option to what you are trying to achieve, since the developer doesn't have to worry about which of his methods are called last.
answered 2013-01-02T14:30:22.020