如何在不将其用作全局变量的情况下在另一个函数中使用它呢?

时间:2019-01-23 16:39:48

标签: javascript function

我正在尝试从“计算年龄”功能中找出如何使用var age 在退休功能中。

 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();

1 个答案:

答案 0 :(得分:0)

您不会直接访问该变量,因为它的作用域是该函数。但是,您可以做的是使这些函数可返回而不是登录这些函数。这样做的好处是模块化。您不需要经常去更新日志语句,只需将它们用作计算函数即可。

例如:

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. ");

另一个选项是通过主对象跟踪值。这有点儿使用全局变量。

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();