Underscore.js _.tap()函数什么是方法链? [英] Underscore.js _.tap() function what is a method chain?

查看:143
本文介绍了Underscore.js _.tap()函数什么是方法链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Underscore.js文档解释了 _。tap()函数点击到方法链中。 http://underscorejs.org/#tap

The Underscore.js documentation explains that the _.tap() function "taps" into a method chain. http://underscorejs.org/#tap

我跟随他们的例子有困难:

I have trouble following their example:

_.chain([1,2,3,200])
  .filter(function(num) { return num % 2 == 0; })
  .tap(alert)
  .map(function(num) { return num * num })
  .value();
=> // [2, 200] (alerted)
=> [4, 40000]

此上下文中的方法链是什么?我一直认为方法链是链接方法的概念: object.foo()。bar()。baz()

What is the method chain in this context? I always thought of method chaining as the concept of chaining methods off of one another: object.foo().bar().baz().

我见过使用这种方法的例子: module.exports = _.tap {},(连接器) - > ,这样做点击进入对象文字的方法链?

I have seen examples using this method: module.exports = _.tap {}, (connectors) ->, so does this "tap" into the object literal's method chain?

推荐答案

来自精细手册


链接

[。 ..]

调用将导致所有将来的方法调用返回包装对象。完成计算后,使用检索最终值。

Chaining
[...]
Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, use value to retrieve the final value.

因此,除了您在包装对象上链接Underscore方法之外,在Underscore上下文中链接与在其他地方链接相同。首先调用 _.chain 来获取包装器:

So chaining in the Underscore context is the same as chaining elsewhere except that you're chaining Underscore methods on a wrapped object. You start by calling _.chain to get your wrapper:

_(obj).chain()

然后你在 _上调用Underscore方法.chain 返回并返回包装对象:

then you call Underscore methods on what _.chain returns and they will return wrapped objects as well:

_(obj).chain()
      .filter(function(x) { ... })
      .map(function(x) { ... })
      ...

最后你调用 _。value 来打开chaining-wrapper:

and finally you call _.value to unwrap the chaining-wrapper:

var result = _(obj).chain()
                   .filter(function(x) { ... })
                   .map(function(x) { ... })
                   ...
                   .value();

返回 _。点按。所有 点击都是这样

Back to _.tap. All tap does is this:

_.tap = function(obj, interceptor) {
  interceptor(obj);
  return obj;
};

所以它调用传递的函数,拦截器对迭代的值进行迭代并返回正在迭代的内容而不对其执行任何操作。 _。点击与以下内容相同:

so it calls the passed function, interceptor on the value being iterated over and returns what is being iterated over without doing anything to it. _.tap is the same as:

.map(function(x) { f(x); return x })

但它使你的意图清楚。实际上, _。tap 可让您查看通过方法链传递的数据,而无需更改该数据。

but it makes your intention clear. In effect, _.tap lets you peek into the data passing through the method chain without altering that data.

这篇关于Underscore.js _.tap()函数什么是方法链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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