2014-03-26 25 views
-1

我似乎无法访问由调用函数定义的参数 - myfunction在被调用的函数method2中。任何想法我做错了什么。我有一种感觉,我正在陷入我不确定的倒闭之中。Javascript范围问题在运行时无法访问变量事件

function myfunction(){ 
     var config = { alpha: 1, beta:2, charlie:3} 
     $(someelement).on('event', function(a,b,config){ 
      //a and b are published established params of the event im using 
      //config is something im adding 
      method2(a, b, config); 
     }); 
    } 
    function method2(a,b,c){ 
     //param c is undefined why ?? 
    } 

回答

2

因为你在你的声明函数参数config

$(someelement).on('event', function(a,b,config){ 
// Here --------------------------------^  
    method2(a, b, config); 
}); 

那阴影(隐藏)的config您在封闭函数声明。如果删除它:

$(someelement).on('event', function(a,b){ 
// Removed ----------------------------^  
    method2(a, b, config); 
}); 

参数不再阴影(隐藏)变量。

问题是该函数的第三个参数也被命名为config,并且当它没有通过时(因为jquery on没有三个参数),它被设置为undefined