使用import * as x作为函数默认参数引发未定义错误的原因
curry variable become undefined in my JavaScript function? Let's break down exactly what's happening here with your code:
First, here's your original code for reference:
import * as curry from './curry-module.js' export function example(curry = curry) { return { foo: (args) => curry.foo(args), bar: (args) => curry.bar(args), } }
When you call example() without arguments, the curry variable inside the function ends up as undefined—and this is all down to JavaScript's scoping and variable initialization rules.
The Root Cause
When you define a function parameter with the same name as an outer variable (in this case, curry), the parameter becomes a local variable that shadows the outer one.
Here's what happens step-by-step when example() runs without arguments:
- The function creates a local
curryparameter variable (this shadows the importedcurryfrom outside). - When trying to set the default value
curry = curry, the right-hand sidecurryrefers to this uninitialized local parameter—not the imported one. - Since local variables are initialized to
undefinedbefore any assignment, you're effectively settingcurry = undefined.
It's equivalent to writing this explicit version:
function example() { let curry; // Local variable, initialized to undefined curry = curry; // Assign undefined to itself // ... rest of the function }
The Fix
The simplest solution is to rename the function parameter so it doesn't clash with the imported variable. This way, the default value will correctly reference the imported curry toolset:
import * as curry from './curry-module.js' export function example(curryUtils = curry) { // Renamed parameter to avoid shadowing return { foo: (args) => curryUtils.foo(args), bar: (args) => curryUtils.bar(args), } }
Now when you call example() without arguments, curryUtils will default to the real imported curry module, and you can still pass a mock version for testing purposes.
内容的提问来源于stack exchange,提问作者worc

