jquery回调

ian*_*ace 3 jquery callback

嗨,有人可以向我解释一下jquery回调的概念有点困在这个简单的代码上

$(document).ready(function(){
    bar('',function(){
        foo();
    });         
});

function foo()
{
    alert('foo');
}

function bar()
{
    alert('bar');
}
Run Code Online (Sandbox Code Playgroud)

因此,foo()首先执行bar(),但使用上面的代码,只foo()执行并且bar不执行.

这是一个jsfiddle链接

no.*_*ing 8

函数是JavaScript中的第一类成员,因此可以分配给变量并作为参数传递给其他函数.回调函数的思想是函数接收的一个(或多个)参数是可以在某些条件下调用的函数引用.在你的情况下,你bar用两个参数调用但从不对这些参数做任何事情bar.JavaScript不会自动回调函数,因为程序员必须这样做.

这可能是你想要的:

$(document).ready(function(){
    bar('',function(){ //this anonymous function maps to the parameter b in bar(a,b)
        foo(); //missing ; can lead to hard to track errors!
    });         
});


function foo()
{
    alert('foo');
}

//accept two parameters
// in this example code, given the call to bar() above, a will map to '' and b to the anonymous function that calls foo()
function bar(a, b) 
{
    alert('bar');
    if(typeof b === 'function'){ //check if b is a function
        b(); //invoke
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

@贾里德的建议无疑更有意义-变化if(b)给if(typeof b === 'function'){调用之前b

  • @ no.good.at.coding - if(typeof b =='function')`怎么样? (2认同)
  • @ianace - 这不会自动发生,开发人员需要确保它的工作方式.例如,jQuery的`ready()`函数采用回调函数.如果你深入研究[jQuery的源代码](http://code.jquery.com/jquery-latest.js),你会看到每次你将回调函数附加到`ready`时,它会被放入阵列.当ready事件触发时,该回调数组中的每个条目都被逐个调用 - jQuery开发人员必须以这种方式编写它,JavaScript只提供了这种设计模式可能的机制. (2认同)