How to detect the string calls in JavaScript?

advertisements
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 func1 and func2 change some state on the this object 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() calls func1 on obj, but func2 is called on a wrapper returned from func1 and this wrapper could be aware of the previous func1 call. If you later call obj.func2().func1() then func2 is now called on obj whereas func1 is called on the wrapper which is aware of the previous func2 call, etc.