javascript es6双箭头功能 [英] javascript es6 double arrow functions

查看:96
本文介绍了javascript es6双箭头功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的头脑包裹在一些反应中常见的箭头函数及其工具上。

I am trying to wrap my head over some of arrow functions that are so common in react and it's tools.

给出以下示例:

    export default function applyMiddleware(...middlewares) {
      return (createStore) => (reducer, preloadedState, enhancer) => {
        // snip actual enhancer logic

        return {
            ...store,
            dispatch
        }
    }
}

用文字描述上述内容:


  1. 我们的导出函数(applyMiddleware)接受带有spread的数组参数。

  2. 然后applyMiddleware返回一个带有createStore参数的无名函数,这次返回另一个无名函数三个参数。

所以如果没有箭头,它将如下所示:

So without the arrows it would look like this:

export default function applyMiddleware(...middlewares) {
  return function(createStore){
      return function(reducer,preloadedState,enhancer){
        //some logic

          return{...store,dispatch}
      }
    }
}

我的问题:


  1. 我是否正确?

  2. 什么是常见用例/代码p我们在这里看到的范式?


推荐答案

你的第一个问题的答案或多或少(见我的评论)。你的第二个问题的答案是你看到的模式是使用关闭 currying 。导出函数的原始参数被收集到一个名为中间件的数组中,返回的函数关闭(即有权访问)。然后可以使用另一个参数'createStore'再次调用该函数,然后返回另一个可以接受更多参数的函数。这允许人们部分地应用参数。对于一个更简单(也许更容易理解)的例子,让我们采用一个名为'add'的函数来添加两个数字:

The answer to your first question is more or less (see my comment). The answer to your second question is that the pattern you are seeing is a combination of using a closure and currying. The original parameters to the exported function get gathered into an array called 'middlewares' that the returned functions close over (i.e. have access to). The function then can be called again with yet another parameter 'createStore' then another function is returned that can accept even more parameters. This allows one to partially apply the parameters. For a more trivial (and perhaps more easily comprehended) example, lets take a function called 'add' that adds two numbers:

let add = (x, y) => x + y;

不是很有趣。但是让我们分解它以便它可以取第一个数字并返回一个占用第二个的函数:

Not very interesting. But lets break it up so it can take the first number and return a function that takes the second:

let add = x => y => x + y;
let add3 = add(3);
let seven = add3(4); // 7

这对我们的添加功能来说似乎不是一个大赢家,但你开始时更合理的现实世界的例子。此外,不是手动调度,而是可以(并且可取)使用咖喱功能为您完成,许多流行的库(lodash,下划线,ramda)为您实现咖喱。使用Ramda的一个例子:

This may not seem like a big win for our add function, but you started with a much more reasonable real-world example. Additionally, rather than currying manually it is possible (and desirable) to use a curry function that does it for you, many popular libraries (lodash, underscore, ramda) implement curry for you. An example using Ramda:

let add = R.curry((x, y) => x + y);
let add3 = add(3);
let five = add3(2);
let also5 = add(3, 2);
let still5 = add(3)(2); // all are equivalent.

这篇关于javascript es6双箭头功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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