js方法链尾 [英] js method chain tail

查看:103
本文介绍了js方法链尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法检测链(流畅接口)中的方法调用是否在该链的TAIL位置?

is there a way to detect if a method call in a chain (fluent interface) is in TAIL position in that chain ?

var some = g.f(arg1).f(arg2).f(arg3);

还是我们绝对需要类似的东西

or do we absolutely need something like

var some = g.f(arg1).f(arg2).f(arg3).end();

我要避免?

返回值对我而言并不那么重要,但是我需要在链的末尾计算一些内容(内部字符串式键),每次调用的长度可能不同.

REturned value is not so important for me, but I need to compute something (an internal string-like key) at the end of the chain, with could have different lengths from one call to another.

推荐答案

不,如果函数调用看起来相同,则由于下一个链接调用尚未发生,并且无法进行检测,因此无法检测给定方法是否位于尾部位置解释器不会为您提供任何证据来证明是否还有另一个链式调用.

No, there is no way to detect if a given method is in the tail position if the function call looks identical because the next chained invocation has not yet happened and the interpreter doesn't offer you any evidence for whether there is another chained invocation coming or not.

您可以根据需要寻找第二个可选参数:

You could make an optional second argument that was the clue you are looking for:

var some = g.f(arg1).f(arg2).f(arg3, "end");

然后,您的f()函数将仅检查第二个参数是否存在并具有适当的值,如果存在,则可以执行尾部操作.

Then, your f() function would just check to see if the second argument was present and had the appropriate value and, if so, it could carry out the tail operations.

或者,您可以制作一个稍有不同的f()版本,称为fTail()(或任何您想调用的名称):

Or, you could make a slightly different version of f() called fTail() (or whatever you want to call it):

var some = g.f(arg1).f(arg2).fTail(arg3);

fTail()可能看起来像这样:

xxx.prototype.fTail = function() {
    var retVal = this.f.apply(this, arguments);

    // now do your tail operations here

    return retVal;
};


正如您所建议的,我认为我会使用一系列的args,因为这似乎可以解决您的所有问题,易于使用并且效果良好:


As you have proposed, I think I'd go with an array of args since that seems to solve all your issues, is easy to use and will perform well:

var some = g.f([arg1, arg2, arg3], fn);

这篇关于js方法链尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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