本文介绍了回调函数示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解如何在下面的代码块中使用 callback()函数。我们如何在函数体中使用 callback()作为函数,当 function callback {} 被定义?什么是将true / false作为参数传递到下面的回调函数中的重现?

I am having a hard time understanding how the callback() function is used in the following code block. How are we using callback() as a function, in the function body, when function callback{} hasn't been defined? What are the reprecussions of passing true / false as paramters into the callback function below?

我感谢任何澄清,提前感谢!

I appreciate any clarification, thanks in advance!

socket.on('new user', function(data, callback){
    if (nicknames.indexOf(data) != -1){
        callback(false);
    }else{
        callback(true);
        socket.nickname = data;
        nicknames.push(socket.nickname);
        updateUserList();
    }
});


推荐答案

当你将函数传递为arugment时,函数,当你通过这个回调函数返回值时,值将是passsed函数的参数,这是回调。

When you pass function as arugment it is known as callback function, and When you return value through this callback function, the value would be parameter of passsed function which is callback indeed.

function myFunction(val, callBack){
    if(val == 1){
        callBack(true);
    }else{
        callBack(false);
    }
}

myFunction(0,
//the true or false are passed from callback()
//is getting here as bool
function (bool){
    if(bool){
        alert("do stuff for when value is true");
    }else {
        //this condition is satisfied as 0 passed
        alert("do stuff for when value is false");
    }
});

基本上callBacks()用于异步概念。

Basically callBacks() are used for asynchronous concepts. It is invoked on particular event.

myFunction 也是在点击事件发生的回调函数。

myFunction is also callback function it's occurred on click event.

document.body.addEventListener('click', myFunction);

这意味着将动作分配给其他人,不要考虑这一点,条件将满足。

It means assign the action to other and don't think about this, the action will be performed when the condition will meet.

这篇关于回调函数示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:40