Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

ecmascript 6 - javascript es6 double arrow functions

I want to better understand es6 arrow functions.

Given the following example:

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

        return {
            ...store,
            dispatch
        }
    }
}

Describing the above in words:

  1. Our exported function (applyMiddleware) takes an array parameter with spread.
  2. Then applyMiddleware returns a nameless function with a createStore parameter, which returns another nameless function this time with three parameters.

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}
      }
    }
}

My questions:

  1. Am I correct?
  2. What is the common use case/code paradigm we see here?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...