javascript

时间:2015-10-02 14:11:50

标签: javascript jquery

如果我将函数传递给具有相同函数名和处理程序名的函数,哪一个会优先?以及如何在需要进行递归的情况下访问这两个内部函数中的每一个以及引用传递的函数。见下面的代码。

var f1,f2;

(function f(f){
    return typeof f(f2); /*please check below comments for output of this line*/
  })(function(f1){ return 1; });

/* this will call the passed function,why not recursion will not happen here? */

3 个答案:

答案 0 :(得分:3)

函数参数优先于函数自己的名称。如果您遮蔽或覆盖变量,则无法访问它(除非它是阴影全局变量)。

解决方案是使用不同的名称。

答案 1 :(得分:0)

递归不会仅仅因为函数的参数优先于函数本身而发生。这是一个显示它的例子:

(function f (f) {
   return f.name;
}) (function funcName () { }); // this will return funcName

如果我们将参数的名称更改为f1,f将成为函数本身的引用

(function f (f1) {
   return f.name;
}) (function funcName () { }); // this will return f

答案 2 :(得分:0)

我看到你使用jquery。所以我想问你在哪里宣布你的职能?内部

    <script type="text/javascript">
     $(document).ready(function(){ 
        function f(){
            return 'this is local function inside anonymous function, so it's invisible for recursion in aside of current document ready'
        }
    });
//or here? 
    function f(){
    return        'this function is a window object property, and must be visible for recursion';
    }    
    </script>
相关问题