在函数内部运行函数

Run a function inside a function

本文关键字:函数 运行 内部      更新时间:2023-09-26

我有这个:

function cool(){
   function alsocool(){
   }
}

然后我运行cool()按钮点击:

$(selector).on('click', function(){
 cool();
}

如何在同一次单击中运行cool()alsocool()注意我不想做:

function cool(){
   function alsocool(){
   }
   alsocool();
}

如果我这样做:

$(selector).on('click', function(){
     cool(); alsocool();
    }

它不起作用。

是否可以在同一调用的函数内部运行函数?

编辑:

我确实想通过cool(),因为很明显,一旦alsocool()的内部函数cool()被识别,但cool();是从许多选择器传递的,因此我想知道从哪个选择器传递并采取适当的行动。

示例我想要这样的东西:

function cool(){
// If this was called by button1, run alsocool() else bypass it
       function alsocool(){
       }
// some code goes here
}
$("#button1").on('click', function(){
         cool(); alsocool();
         // If button1 clicked, run cool AND alsocool
        }
$("#button2").on('click', function(){
         cool(); // If button2 clicked, run cool ONLY.
    }

答案很简单:这是不可能的
内部函数是包含函数作用域的本地函数,因此除非该函数调用它,否则根本无法调用它。

如果希望两个函数都可以从外部访问,请在cool之外定义alsocool,即与cool处于同一级别。


根据您的评论,这里有一种方法可以使用参数来确定是否应该调用内部函数:

function cool(callInner){
    function alsocool(){
    }
    if(callInner) {
        alsocool();
    }
}

如果进行

function cool() {
   function alsocool() { ... }
}

则"alsocoll"仅在执行cool()函数时存在。它将无法从外部访问。

你会想要:

function cool() { ... }
function alsocool() { ... }
$(selector).click(function() {
   cool();
   alsocool();
}):

问题是,因为您在cool中定义了函数alsocool,所以它的可见性仅限于该范围。

因此,只能cool中调用函数alsocool

当然,您可以将alsocool的声明移到cool之外,这样仍然允许您从cool中调用alsocool,但将从alsocool中释放对cool作用域的访问权限。

如果这对您来说是一个可行的选项,您也可以根据传递的参数来限制coolalsocool的调用;

function cool(alsoAlsoCool){
   function alsocool(){
   }
   if (alsoAlsoCool) {
       alsocool();
   }
}
// cool(true) will call it, but cool() or cool(false) won't.

你不能那样做。alsocool只存在于cool内部,点击处理程序不知道alsocool的存在。

如果你不想从cool内部调用alsocool,那么你必须使alsocool全局化。

我不明白你为什么要这样做,但你可以这样做:

function cool()
{
    arguments.callee.alsoCool = function() {
        alert("also cool");
    };
    alert("cool");
}
$("#b").click(function() {
    cool();
    cool.alsoCool();
});

现场演示:http://jsfiddle.net/ENqsZ/

或者,正如火箭公司建议的那样,你可以这样做:

function cool()
{
    alert("cool");
    return function() {
        alert("also cool");
    };
}
$("#b").click(function() {
    var alsoCool = cool();
    alsoCool();
});