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

如何在JavaScript中向嵌套子函数传递参数?代码示例求助

如何调用内部函数并正确传递参数

原代码的问题

  • salary 和 salary_with_tax 是 checkSalary 的内部函数,外部默认无法直接访问。
  • 内部函数声明了和外部函数同名的参数(比如salary里的baseSalary),会遮蔽外部的变量,调用时不传参就会得到undefined。
  • salary_with_tax 里调用 salary() 没有传参,导致计算结果为NaN。

解决方案1:通过闭包复用初始参数并暴露内部函数

修改checkSalary,让它返回包含内部函数的对象,同时内部函数直接使用外部函数的参数(避免参数遮蔽):

function checkSalary(baseSalary, bonus, tax) {
    console.log(baseSalary, bonus, tax);
    
    // 直接使用外部函数的baseSalary和bonus,不再声明同名参数
    function salary() {
        console.log(baseSalary, bonus);
        return baseSalary + bonus;
    }
    
    function salary_with_tax() {
        console.log(tax);
        return salary() - tax;
    }
    
    // 暴露内部函数给外部
    return {
        salary,
        salary_with_tax
    };
}

// 先初始化checkSalary,获取内部函数的引用
const calculator = checkSalary(5000, 3000, 100);

// 调用内部函数
console.log(calculator.salary()); // 输出5000 3000,返回8000
console.log(calculator.salary_with_tax()); // 输出100,返回7900

解决方案2:让内部函数支持动态传参

如果需要动态修改参数值,可以给内部函数设置默认参数,既可以复用初始值,也能传入新值:

function checkSalary(baseSalary, bonus, tax) {
    console.log(baseSalary, bonus, tax);
    
    // 内部函数接受参数,默认值为外部函数的参数
    function salary(newBase = baseSalary, newBonus = bonus) {
        console.log(newBase, newBonus);
        return newBase + newBonus;
    }
    
    function salary_with_tax(newTax = tax, customBase, customBonus) {
        console.log(newTax);
        // 可以传递自定义的薪资和奖金给salary
        return salary(customBase, customBonus) - newTax;
    }
    
    return {
        salary,
        salary_with_tax
    };
}

const calculator = checkSalary(5000, 3000, 100);

// 使用初始参数调用
console.log(calculator.salary()); // 8000
console.log(calculator.salary_with_tax()); // 7900

// 传入新参数调用
console.log(calculator.salary(6000, 4000)); // 10000
console.log(calculator.salary_with_tax(200, 6000, 4000)); // 9800

内容的提问来源于stack exchange,提问作者Flo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:06:24