如何在JavaScript中检测链接的函数调用? [英] How to detect chained function calls in JavaScript?

查看:61
本文介绍了如何在JavaScript中检测链接的函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();

函数 _hasChainedFunc()是否可以实现?此函数应该在第一次调用时返回 true (因为随后会调用func2()),在第二次调用时返回 false .

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.

在更高级的版本中, _hasChainedFunc()也可能返回此函数,此函数随后将被实际调用.

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.

相反,可以 检查当前呼叫之前是否在之前链接了先前的呼叫.这仅需要您在对象中保留有关先前调用的某些状态,并在每次在其上调用新函数时对其进行更新.如果只使用一个调用链,则可以通过使 func1 func2 更改 this 对象上的某些状态来实现,然后再返回.

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.

如果要在同一对象上调用多个链,则会遇到如何检测链结束的问题.为此,您将需要使每个链接函数返回一个包装器,该包装器将围绕原始 this ,该包装器将存储有关先前调用的状态.

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.

如果使用包装方法,则 obj.func1().func2()会调用 obj 上的 func1 ,但是会调用 func2在从 func1 返回的包装器上调用,并且该包装器可以知道先前的 func1 调用.如果以后再调用 obj.func2().func1(),则现在在 obj 上调用 func2 ,而 func1 在知道先前 func2 调用等的包装器上调用.

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.

这篇关于如何在JavaScript中检测链接的函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆