You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用import * as x作为函数默认参数引发未定义错误的原因

Why does the 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:

  1. The function creates a local curry parameter variable (this shadows the imported curry from outside).
  2. When trying to set the default value curry = curry, the right-hand side curry refers to this uninitialized local parameter—not the imported one.
  3. Since local variables are initialized to undefined before any assignment, you're effectively setting curry = 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:18:06