第一个函数使用第二个函数的变量,但第二个函数也调用第一个函数

时间:2017-07-20 15:05:37

标签: javascript function invoke

我有这段JavaScript代码,我希望它能够在第二个函数中使用calculate()(它确实有用),但问题是第一个函数使用了第二个函数中声明的变量功能。此外,我只需要在调用var first=prompt时执行chemicalcalc

function calculate(){
  var calctrans=parseInt(firsttrans, 10)
  return calctrans;
}

function chemicalcalc(){
  var first=prompt("Enter first term\nLeave bank to go back to element finder");
  if(first==""){
    calculate();
  }else{
    var firsttrans=first.replace("h", 1);
  }
}

chemicalcalc();

1 个答案:

答案 0 :(得分:0)

通过将calculate()嵌套在chemicalcalc内,允许calculate访问父函数的范围。

但是,如果用户没有输入任何内容并且只是在提示符下点击ENTER,那么您的代码将调用calculate,然后会尝试使用firsttrans,而不会有一个值,因为没有输入设置值的if的分支,所以你有一个逻辑错误。

我删除了if/then逻辑,以显示函数的其余部分如何工作。

function chemicalcalc(){
  var first = prompt("Enter first term\nLeave bank to go back to element finder");
  
  var firsttrans = first.replace("h", 1);
  
  // Invoke calculate and return whatever it returns
  return calculate();
  
  // Nested functions always have access to the parent's scope
  function calculate(){
    var calctrans = parseInt(firsttrans, 10)
    return calctrans;
  }
}

console.log(chemicalcalc());

另一个选项(而不是嵌套函数)是简单地将第二个函数传递给它所需的数据作为参数:

function chemicalcalc(){
  var first = prompt("Enter first term\nLeave bank to go back to element finder");
  
  var firsttrans = first.replace("h", 1);
  
  // Invoke calculate and pass it the data it needs, then return whatever it returns
  return calculate(firsttrans);
}

// Now the function expects data to be passed by the caller
function calculate(data){
  var calctrans = parseInt(data, 10)
  return calctrans;
}

console.log(chemicalcalc());

相关问题