简体   繁体   中英

How to use one function's variable in another function without it being a global variable?

I'm trying to figure out how to use the var age from the calculate age function in the retirement function.

 var year = prompt(" Enter year of birth: ");

function calcAge(Year){
    var age = 2019 - year;
    console.log(" Your age is " + age);
}

var retAge = prompt(" What age do you plan to retire? ");

function calcRet(retAge){
    var yearsToRet = retAge - age;
    console.log(" You have " + yearsToRet + " to retire. ");
}

calcAge();
calcRet();

You don't directly access the variable as it is scoped to that function. What you could do however is make those functions returnable instead of logging in the functions. The benefit here is modularity. You don't need to constantly go update your log statements, you can just use these as calculation functions.

Eg:

 var year = prompt(" Enter year of birth: "); function calcAge(Year){ return 2019 - year; } var retAge = prompt(" What age do you plan to retire? "); function calcRet(){ return retAge - calcAge(year); } console.log('Your age is: ' + calcAge()); console.log(" You have " + calcRet()+ " years to retire. "); 

Another option is to track the values via a main object. This is kinda sorta uses a global var however.

 var responses = {} responses['year'] = prompt(" Enter year of birth: "); function calcAge(){ responses['age'] = 2019 - responses.year; console.log(" Your age is " + responses.age); } responses['retAge'] = prompt(" What age do you plan to retire? "); function calcRet(retAge){ var yearsToRet = responses.retAge - responses.age; console.log(" You have " + yearsToRet + " to retire. "); } calcAge(); calcRet(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM