我有这个:
function cool(){
function alsocool(){
}
}
我在按钮单击时运行cool():
$(selector).on('click', function(){
cool();
}
如何通过同一次点击运行 cool()
和 alsocool()
?请注意,我不' t 想做:
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();
}
}
关于javascript - 在函数内运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8853588/