JavaScript中如何获取对象内函数的私有变量totalSalary的取值
你代码中的totalSalary是finalSalary函数内部的局部变量,作用域仅局限于函数内部,函数执行完成后该变量就会被JS引擎回收,因此无法直接在函数外部访问该变量。
推荐解决方案:修改返回值结构
把finalSalary的返回值从单一的sellsBonus改为包含多个需要字段的对象,调用时即可按需取对应值:
const info = { firstName: "Richard", lastName: "Benson", mainSalary: 250000, monthlySell: 1000000, finalSalary: function(bonusParcent) { const sellsBonus = this.monthlySell * bonusParcent; const totalSalary = this.mainSalary + sellsBonus; // 返回包含两个属性的对象 return { sellsBonus, totalSalary }; } } console.log("Full name: " + info.firstName + " " + info.lastName); console.log("Main salary: $", info.mainSalary); const salaryRes = info.finalSalary(0.05); console.log("Sells bonus: $", salaryRes.sellsBonus); console.log("Total salary: $", salaryRes.totalSalary);
其他可选方案:挂载为对象属性
如果你不想修改原有返回值结构,可以把totalSalary挂载为info对象的属性,调用后直接从对象上取值:
const info = { firstName: "Richard", lastName: "Benson", mainSalary: 250000, monthlySell: 1000000, finalSalary: function(bonusParcent) { const sellsBonus = this.monthlySell * bonusParcent; // 将totalSalary挂载到当前对象上 this.totalSalary = this.mainSalary + sellsBonus; return sellsBonus; } } console.log("Full name: " + info.firstName + " " + info.lastName); console.log("Main salary: $", info.mainSalary); console.log("Sells bonus: $", info.finalSalary(0.05)); console.log("Total salary: $", info.totalSalary);
注意:该方案会给info对象新增额外属性,多次调用finalSalary传入不同提成比例时,totalSalary的值会被最新的调用结果覆盖。
内容的提问来源于stack exchange,提问作者user13899130
相关产品推荐
相关产品推荐

