gpt4 book ai didi

javascript - 如何在 javaScript (Node.Js) 中将私有(private)变量导出到公共(public)变量

转载 作者:行者123 更新时间:2023-12-03 09:50:53 24 4
gpt4 key购买 nike

比如我有这样一个计算程序:

function cal(salary, additionalSalary) {
var salary;
var additionalSalary;
var totalPay = salary + additionalSalary;
}

function 401k() {
var specialAccount = totalPay * 0.37;
var normalAccount = totalPay - specialAccount;
}

我的问题是如何从函数中导出 totalPay 变量,使其成为在 401k 函数中使用的公共(public)变量。谢谢。

最佳答案

您可以使用 closuresimmediately invoked function在薪水计算中处理 let totalPay 变量的表达式:

代码:

const Salary = (() => {
let totalPay
const cal = (salary, additionalSalary) => {
totalPay = salary + additionalSalary
}
const k401 = () => {
const specialAccount = totalPay * 0.37
const normalAccount = totalPay - specialAccount
return normalAccount
}
return {
cal: cal,
k401: k401
}
})()

// Use it like this
Salary.cal(5000, 250)
const k401 = Salary.k401()

console.log('k401:', k401)

关于javascript - 如何在 javaScript (Node.Js) 中将私有(private)变量导出到公共(public)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59062841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com