定义与参数_简单的回调函数例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模块模式</title>
    <script src="../unitl/test.js"></script>
    <style>
        #results li.pass {color:green;}
        #results li.fail {color:red;}
    </style>
</head>
<body>

    <ul id="results"></ul>

    
</body>


<script>


    var text = "Demo arigato!";

    report("Before defining funcations");


    //函数定义,参数为一个回调函数,其函数内立即调用该回调函数
    function unless(ninjaCallback) {
        report("In unless function");
        return ninjaCallback();
        
    }


    function getText() {

        report("In getText function");
        return text;

    }

    report("Before making all the calls");

    assert(unless(getText)===text,"The unless function works!" + text);

    report("After the calls have been made");


</script>
</html>

接下来我们来看看看这个简单函数是如何执行的,首先执行这一句。

紧接着执行回调函数

如图,useless(getText)调用后的执行流。getText作为参数传入useless函数并调用。useless函数体内对传入函数进行调用,本例中促发了getText函数的执行。(即我们对getText函数进行回调)。

完成这个过程很容易,原因就在于javascript的函数式本质让我们能把函数作为第一类对象。更进一步说,我们的代码可以写成如下形式:

var text = 'demo arigato';

function useless(ninjaCallback) {
     return ninjaCallback();
}
//直接以参数形式定义回调函数。
assert(useless(function(){return text})===text,"The useless function works!" + text);

posted @ 2020-12-08 16:20  yongjar  阅读(133)  评论(0编辑  收藏  举报