工作函数如何返回带有另一个参数的另一个函数?

时间:2018-12-28 09:35:21

标签: javascript reactjs redux react-redux

我具有Dan Abramov的redux课程中的功能。它需要存储但返回以操作为参数的函数。我知道clojures,但是在功能上我们并没有执行最后的功能。 addLoggingToDispatch函数没有操作参数,该函数如何工作?

     const addLoggingToDispatch = (store) => {
     const rawDispatch = store.dispatch;

      return (action) => {
       console.group(action.type);
       console.log('%c prev state', 'color: gray', store.getState());
       console.log('%c action', 'color: blue', action);
       const returnValue = rawDispatch(action);
       console.log('%c next state', 'color: green', store.getState());
       console.groupEnd(action.type);
       return returnValue;
      };
     };

2 个答案:

答案 0 :(得分:2)

addLoggingToDispatch返回的函数关闭{em> store参数。然后,在调用该函数时,将为action传递参数。因此,当返回的函数正在运行时,它可以访问action(因为它是它的参数之一) store(因为它在addLoggingToDispatch上关闭) s参数)。

当一个函数在另一个函数内部创建并且内部函数在外部函数返回后继续存在(因为外部函数返回了它,或者已将其添加到事件处理程序列表等函数列表中),内部函数与创建该函数的上下文(对外部函数的调用)以及该上下文的所有范围内参数/变量(在此示例中为store)之间具有持久的联系。

这是一个更简单的示例:

function createAdderFunction(a) {
  return function(b) {
    return a + b;
  };
}

var addFive = createAdderFunction(5);
// Now, `addFive` is a function that will add 5 to whatever you call it with
console.log(addFive(2));  // 7
console.log(addFive(37)); // 42

var addTen = createAdderFunction(10);
// And `addTen` is a function that will add 10 to whatever you call it with
console.log(addTen(15)); // 25

// `addFive` and `addTen` are separate from each other and work independently
console.log(addFive(0)); // 5
console.log(addTen(0));  // 10

答案 1 :(得分:2)

该函数似乎旨在替换或包装商店随附的dispatch方法。 dispatch方法将操作作为参数,因此它具有与返回函数相同的签名。因此,无论您在哪里实际创建商店,都可以执行以下操作:

const store = createStore()
store.dispatch = addLoggingToStore(store)

您可以通过向我们展示您实际使用addLoggingToStore的位置来阐明此帖子。但是,如果我正确理解,则此功能的目的是在不创建任何其他日志中间件的情况下烘烤日志功能。现在,每当调用dispatch(someAction)时,它将运行您的函数,而不是redux存储库提供的默认函数。