在函数内部运行函数
Run a function inside a function
我有这个:
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
作用域的访问权限。
如果这对您来说是一个可行的选项,您也可以根据传递的参数来限制cool
中alsocool
的调用;
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();
});
- 关注函数运行过的表单字段(新手)
- 在函数运行时显示对话
- Javascript - 加载函数运行时未定义的变量
- Javascript变量在函数运行后不断重置自身
- 如何让 setTimeout 函数运行,然后停止使用循环
- 如何在函数运行之前隐藏 CSS
- 使用 .on 函数运行 jQuery 声明函数
- 在函数运行期间关闭 onClick
- jQuery停止函数运行两次
- Javascript:如何在函数运行完成之前对文档进行更改
- nodejs - 为什么我的异步函数运行两次
- 在传递值后停止函数运行
- 如何在 javascript 中的函数中将字符串作为函数运行
- 如何停止计时器函数运行
- 在浏览器空闲后保持设置超时函数运行
- JQuery:阻止一个函数运行,直到满足另一个函数条件“X”时间
- Angular 提供程序服务需要 init 函数运行一次
- 更新 Angular $interval 中的变量会导致其他函数运行
- 如何阻止此 setTimeout 函数运行
- 传入函数数组作为参数,对于函数中的每个函数运行函数