繁体   English   中英

这个javascript回调函数如何工作?

[英]How does this javascript callback function work?

任何人都可以逐行解释,我不知道此回调和原型如何工作,尤其是js文件中的函数(回调)

user.getUsers(function (theUsers) {
     $('#users-table-wrapper').html(user.getATable(theUsers));
});

HTML中的这一部分

Js文件

function User () {

}
User.prototype.getUsers = function (callback) {
    $.ajax({
        url: 'posting.php',
        data: {
            request:'get-users'
        },
        type:'post',
        dataType: 'json',
        success: function(users){
//            callback(users);
            if (callback) { callback(users); }
        }
    });
}

这是我的index.html

没有声明theUser,但仍然可以使用。 据我所知,当我输入funcion(theUser)时,User是一个参数或参数。 必须在某处声明它。

似乎他们俩都不是...。这是怎么工作的?

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="User.js"></script>
    <script>
        $(function () {
            var user = new User();
            user.getUsers(function (theUsers) {
                $('#users-table-wrapper').html(user.getATable(theUsers));
            });
        });   
    </script>
</head>
<body>
    <div class='main-wrapper'>
        <h3>Users</h3>
       <div id="users-table-wrapper">
       </div>
    </div>    
</body>
</html>

theUsers是您作为回调提供的匿名函数的参数:

function (theUsers) {
 $('#users-table-wrapper').html(user.getATable(theUsers));
});

User.getUsers的成功方法中,您将看到它的工作方式如下:

success: function(users){
            if (callback) { callback(users); }
        }

因此,如果AJAX调用成功,并且定义了回调,则包含成功检索到的数据的users参数将作为第一个参数传递给回调函数。 由于第一个参数在您的匿名回调定义中被命名为theUsers ,因此它就出现在方法中,从而可用于user.getATable(theUsers)

theUser是函数的命名参数。

调用该函数时,它将获取传递的第一个参数的值。
您在这里调用该函数:

callback(users); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM