本文共 927 字,大约阅读时间需要 3 分钟。
计算机编程中,”回调“是可执行代码的参考,或者是一段可执行程序,”回调“被当做参数传入另外的代码中。这种”回调“机制允许软件底层代码调用上层定义的函数。
很多人对”回调“感到困惑是因为这个”回调“这个名字在作怪。
一个回调方法可以作为参数传入另外一个方法中,回调方法的执行是某些事件所激发的。参数的”调回“本质是,一旦父方法执行完,作为参数的回调方法(回调函数)就会被调用。也就是说父方法调回执行作为参数传过来的方法。
//An innocuous looking method which will become known as a callback method//because of the way in which we will invoke it.function meaningOfLife() { log("The meaning of life is: 42");}//An innocuous looking method which just takes an int and prints it to screen, and takes a function reference to be executed when printANumber completesfunction printANumber(int number, function callbackFunction()) { print("The number you provided is: " + number);}function event() { printANumber(6, meaningOfLife());}
The number you provided is: 6The meaning of life is: 42
之所以叫回调函数,是因为在那些含有指针概念的编程语言中有这样的叫法。如果你的编程语言没有指针概念,那么就可以不去关心回调函数的执行细节。仅仅把它理解成一个函数作为参数被另外一个函数调用就成了。因此,无论父函数什么时候被调用(不论什么情况:按钮点击,定时器到时),当父函数执行完后,回调函数就会被调用。
转载地址:http://zcuwz.baihongyu.com/