Javascript回调函数与仅调用函数

时间:2014-08-08 02:42:05

标签: javascript callback

所以我真的不明白"回调"。

以下是回调示例:

function sayBye(){
   alert("Bye!");
}

function saySeeYou(){
   alert("See you!");
}

function sayHello(name,myfunc){
   alert("Hello");
   myfunc;
}

sayHello("Max",saySeeYou());

当你可以调用函数时,传递函数是什么意思?像这样的代码完全相同:

function sayBye(){
   alert("Bye!");
}

function saySeeYou(){
   alert("See you!");
}

function sayHello(name){
   alert("Hello");
   saySeeYou();
}

sayHello("Max");

3 个答案:

答案 0 :(得分:2)

  

当你可以调用函数时,传递函数是什么意思?

通常,回调Javascript在Javascript中用于您希望将来运行的代码。最简单的例子是setTimeout:如果你现在调用回调,那么代码会立即运行而不是500毫秒之后。

//prints with a delay
console.log("Hello");
setTimeout(function(){
   console.log("Bye");
}, 500);

//no delay this time
console.log("Hello");
console.log("Bye");

当然,如果我们可以按照

的方式写一些内容,那将会非常巧妙
//fake Javascript:
console.log("Hello");
wait(500);
console.log("Bye");

但遗憾的是,Javascript并没有让你这样做。 Javascript是严格单线程的,因此编写wait函数的唯一方法是暂停页面中任何脚本的执行500毫秒,这将“冻结”处于无响应状态的事物。因此,需要很长时间才能完成的操作(如超时或AJAX请求)通常会在完成后使用回调来发出信号,而不是阻止执行,然后在完成时返回。


顺便说一下,当传递回调时,你应该只传递函数名。如果添加括号,则调用函数并传递其返回值:

//When you write
foo(10, mycallback());

//You are actually doing
var res = mycallback();
foo(10, res);
//which will run things in the wrong order 

答案 1 :(得分:0)

你的代码不正确,正如Felix Kling已经指出的那样。除此之外,传递函数而不是直接调用函数允许您插入不同的行为,您的代码更加分离和灵活。这是一个例子:

function sayBye(){    
    alert("Bye!");    
}

function saySeeYou(){    
    alert("See you!");   
}

function sayHello(name,myfunc){    
    alert("Hello");
    if (myfunc) {  
       myfunc();    
    }
}

sayHello("Max",saySeeYou);

// I'm inserting a different behavior. Now instead of displayng "See you!" 
// will show "Bye!". 
sayHello("Max",sayBye); 

答案 2 :(得分:0)

你做错了,你应该像下面那样做

不要调用该函数只是将函数作为回调传递

使用此

sayHello("Max",saySeeYou); //here the second parameter is function

而不是

sayHello("Max",saySeeYou());//This will put the result of saySeeYou as second parameter

in hello call the functiom

function sayHello(name,myfunc){
    console.log("Hello");
    myfunc();
}
相关问题