乐闻世界logo
搜索文章和话题

What is [[ Scopes ]] in dispatch() of redux

1个答案

1

In JavaScript, when dealing with closures or function calls, you'll see an internal property called [[Scopes]] in the debugger. The [[Scopes]] property contains a hierarchical list of the lexical environments for the current execution context, which store captured variables and function definitions.

In the context of Redux's dispatch() function, the [[Scopes]] property is also applicable. When you define a dispatch() in Redux, it may access variables from external scopes, such as middleware, enhancers, or the Redux store itself. References to these external variables are stored in [[Scopes]] to allow access to the correct data and resources during function execution.

Example

Suppose you have a Redux middleware that adds additional logging during dispatch() calls:

javascript
function loggerMiddleware(store) { return function(next) { return function(action) { console.log('dispatching', action); let result = next(action); console.log('next state', store.getState()); return result; }; }; }

In this middleware's dispatch() function, the store and next variables are captured from the outer function. When you pause execution in the browser's JavaScript debugger and inspect the function, you'll typically find these captured variables stored in the [[Scopes]] property.

This [[Scopes]] property enables dispatch() to correctly reference store and next variables during execution, even though they are defined in the outer function. This is a typical application of JavaScript closures and a common pattern in Redux architecture, ensuring functions can access the necessary resources and data in their execution context.

2024年6月29日 12:07 回复

你的答案