var Obj = {
func1 : function() {
// some code
if (this._hasChainedFunc()) {
// block should be CALLED
}
return this;
},
func2 : function() {
// some code
if (this._hasChainedFunc()) {
// block should be NOT called
}
return this;
},
_hasChainedFunc : function() {
// code which detects if there is a chained function???
}
}
Obj.func1().func2();
Is there a possible implementation for function _hasChainedFunc()? This function should return true on the first call (because func2() is called afterwards), false on the second call.
In a more advanced version, _hasChainedFunc() may also returned the function which is actually called afterwards.
Technically you can never know in advance whether there’s another call chained after the current call — this plainly doesn’t make sense because it implies you’re aware of some code that’s gonna be called before it’s called. You can’t do this without a pre-compiler, which I guess is not what you’re after.
Conversely, it is possible to check whether there’s been a previous call chained before the current call. This just requires you to keep some state in the object regarding the previous calls, and update it whenever you call a new function on it. If you only use one chain of calls, you can do this by making
func1andfunc2change some state on thethisobject before returning it.If you want to call multiple chains on the same object, you face the problem of how to detect the end of a chain. For this you will need to make each chained function return a wrapper around the original
this, which would store the state about the previous calls.If you use the wrapper approach,
obj.func1().func2()callsfunc1onobj, butfunc2is called on a wrapper returned fromfunc1and this wrapper could be aware of the previousfunc1call. If you later callobj.func2().func1()thenfunc2is now called onobjwhereasfunc1is called on the wrapper which is aware of the previousfunc2call, etc.