为什么我的全局变量不起作用?

时间:2015-08-09 21:41:34

标签: javascript function scope

我确定这是一个愚蠢/简单的问题,但它确实令我感到困惑。我理解全局范围'以及函数如何访问全局变量及其内部变量。

出于某种原因,我的测试'功能,无法访问全局变量。当我的测试'功能'警报'全局变量它返回0但是当我移动那些全局变量时#39;变量到本地'它起作用的变量。

为什么我的全局变量不起作用?

我的问题是针对变量'年'和'月'

此警报的0(全局范围)(关于年份变量):

//Varibles
var mortgageAmount = getById('mAmount');
var mortgageAmountOutput = logger('mAmount');
var calc = getById('calculateBtn');
var years = +document.getElementById('mPeriod').value;
var months = years*12;


//Functions
function test() {
  //Test to see if numbers are 'numbers'
  //Populate Page
  populateMortgage();
  populateIntRate();

  //Math

  alert("My Mortgage is for: " + years + " years, or for " + months + " months " );



}

当我将变量声明从全局范围移动到本地时,它可以正常工作:

//Varibles
var mortgageAmount = getById('mAmount');
var mortgageAmountOutput = logger('mAmount');
var calc = getById('calculateBtn');

//Functions
function test() {
  //Test to see if numbers are 'numbers'
  //Populate Page
  populateMortgage();
  populateIntRate();

  //Math  
  var years = +document.getElementById('mPeriod').value;
  var months = years*12;

  alert("My Mortgage is for: " + years + " years, or for " + months + " months " );

}

0 个答案:

没有答案