【JavaScript】Understanding callback functions in Javascript

Callback functions are extremely important in Javascript. They’re pretty much everywhere. Originally coming from a more traditional C/Java background I had trouble with this (and the whole idea of asynchronous programming), but I’m starting to get the hang of it. Strangely, I haven’t found any good introductions to callback functions online — I mainly found bits of documentation on the call() and apply() functions, or brief code snippits demonstrating their use — so, after learning the hard way I decided to try to write a simple introduction to callbacks myself.

Functions are objects

To understand callback functions you first have to understand regular functions. This might seen like a “duh” thing to say, but functions in Javascript are a bit odd.

Functions in Javascript are actually objects. Specifically, they’re Function objects created with the Function constructor. A Function object contains a string which contains the Javascript code of the function. If you’re coming from a language like C or Java that might seem strange (how can code be a string?!) but it’s actually run-of-the-mill for Javascript. The distinction between code and data is sometimes blurred.

1 // you can create a function by passing the
2 // Function constructor a string of code
3 var func_multiply = new Function("arg1""arg2""return arg1 * arg2;");
4 func_multiply(5,10); // => 50

One benefit of this function-as-object concept is that you can pass code to another function in the same way you would pass a regular variable or object (because the code is literally just an object).

Passing a function as a callback

Passing a function as an argument is easy.

01 // define our function with the callback argument
02 function some_function(arg1, arg2, callback) {
03     // this generates a random number between
04     // arg1 and arg2
05     var my_number = Math.ceil(Math.random() *
06         (arg1 - arg2) + arg2);
07     // then we‘re done, so we‘ll call the callback and
08     // pass our result
09     callback(my_number);
10 }
11 // call the function
12 some_function(5, 15, function(num) {
13     // this anonymous function will run when the
14     // callback is called
15     console.log("callback called! " + num);
16 });

It might seem silly to go through all that trouble when the value could just be returned normally, but there are situations where that’s impractical and callbacks are necessary.

Don’t block the way

Traditionally functions work by taking input in the form of arguments and returning a value using a return statement (ideally a single return statement at the end of the function: one entry point and one exit point). This makes sense. Functions are essentially mappings between input and output.

Javascript gives us an option to do things a bit differently. Rather than wait around for a function to finish by returning a value, we can use callbacks to do it asynchronously. This is useful for things that take a while to finish, like making an AJAX request, because we aren’t holding up the browser. We can keep on doing other things while waiting for the callback to be called. In fact, very often we are required (or, rather, strongly encouraged) to do things asynchronously in Javascript.

Here’s a more comprehensive example that uses AJAX to load an XML file, and uses the call() function to call a callback function in the context of the requested object (meaning that when we call the this keyword inside the callback function it will refer to the requested object):

01 function some_function2(url, callback) {
02     var httpRequest; // create our XMLHttpRequest object
03     if (window.XMLHttpRequest) {
04         httpRequest = new XMLHttpRequest();
05     else if (window.ActiveXObject) {
06         // Internet Explorer is stupid
07         httpRequest = new
08             ActiveXObject("Microsoft.XMLHTTP");
09     }
10  
11     httpRequest.onreadystatechange = function() {
12         // inline function to check the status
13         // of our request
14         // this is called on every state change
15         if (httpRequest.readyState === 4 &&
16                 httpRequest.status === 200) {
17             callback.call(httpRequest.responseXML);
18             // call the callback function
19         }
20     };
21     httpRequest.open(‘GET‘, url);
22     httpRequest.send();
23 }
24 // call the function
25 some_function2("text.xml"function() {
26     console.log(this);
27 });
28 console.log("this will run before the above callback");

In this example we create the httpRequest object and load an XML file. The typical paradigm of returning a value at the bottom of the function no longer works here. Our request is handled asynchronously, meaning that we start the request and tell it to call our function when it finishes.

We’re using two anonymous functions here. It’s important to remember that we could just as easily be using named functions, but for sake of brevity they’re just written inline. The first anonymous function is run every time there’s a state change in our httpRequest object. We ignore it until the state is 4 (meaning it’s done) and the status is 200 (meaning it was successful). In the real world you’d want to check if the request failed, but we’re assuming the file exists and can be loaded by the browser. This anonymous function is assigned tohttpRequest.onreadystatechange, so it is not run right away but rather called every time there’s a state change in our request.

When we finally finish our AJAX request, we not only run the callback function but we use the call() function. This is a different way of calling a callback function. The method we used before of just running the function would work fine here, but I thought it would be worth demonstrating the use of the call() function. Alternatively you could use the apply()function (the difference between the two is beyond the scope of this tutorial, but it involves how you pass arguments to the function).

The neat thing about using call() is that we set the context in which the function is executed. This means that when we use the this keyword inside our callback function it refers to whatever we passed as the first argument for call(). In this case, when we refer to this inside our anonymous callback function we are referring to the responseXML from the AJAX request.

Finally, the second console.log statement will run before the first, because the callback isn’t executed until the request is over, and until that happens the rest of the code goes right on ahead and keeps running.

Wrapping it up

Hopefully now you should understand callbacks well enough to use them in your own code. I still find it hard to structure code that is based around callbacks (it ends up looking like spaghetti… my mind is too accustomed to regular structured programming), but they’re a very powerful tool and one of the most interesting parts of the Javascript language.

http://recurial.com/programming/understanding-callback-functions-in-javascript/

【JavaScript】Understanding callback functions in Javascript

时间: 2024-10-06 20:39:03

【JavaScript】Understanding callback functions in Javascript的相关文章

【转】onclick事件与href='javascript:function()'的区别

href='javascript:function()'和onclick能起到同样的效果,一般来说,如果要调用脚本还是在onclick事件里面写代码,而不推荐在href='javascript:function()' 这样的写法,因为 href 属性里面设置了js代码后,在某些浏览器下可能会引发其他不必要的事件.造成非预期效果. 而且 onclick事件会比 href属性先执行,所以会先触发 onclick 然后触发href,所以如果不想页面跳转,可以设置 onclick里面的js代码执行到最后

【转】console.time 简单分析javascript动态添加Dom节点的性能

本文代码约定 1 el: 指的是增加直接点的DOM节点 2 totalNum: 为100000(值越大越能体现差距)指的是循环创建的DOM节点 3 for(var i=0;i<totalNum;i++){}: 我们用for来表示就好了,简写代码 如果叫你用javascript动态增加DOM节点,你有哪几种思路呢? 1 .使用innerHTML和字符串拼接 console.time("time1"); var str = ""; for{ str += &quo

【转】巧用局部变量提升javascript性能

转自:http://www.jb51.net/article/47219.htm 巧用局部变量可以有效提升javascript性能,下面有个不错的示例,大家可以参考下 javascript中一个标识符所在的位置越深,它的读写速度也越慢.因此,函数中读写局部变量总是最快的,而读写全局变量通常是最慢的.一个好的经验法则是:如果某个跨作用域的值在函数中被引用一次以上,那么就把它存储到局部变量里. 例如: 复制代码代码如下: <!-- 优化前 --> <script type="tex

【Servlet】Servlet3.0与纯javascript通过Ajax交互

这是一个老生常谈的问题,对于很多人来说应该很简单.不过还是写写,方便Ajax学习的后来者.虽然js.html是一个纯静态的页面,但是以下的程序必须挂在Tomcat服务器上,才能做到Ajax交互,否则看不出效果的.Eclipse for javaee注意把做好的工程挂在Tomcat上,才运行Tomcat.本工程除了JSP必须的Servlet包以外,无须引入其它东西.其实想直接用一个JSP页面完成这个工程的,但是现在搞JSP的,基本上没有人直接在.jsp文件中写东西了吧?后台动作都扔到.java里面

【原创】开发一个完整的JavaScript组件

作为一名开发者,大家应该都知道在浏览器中存在一些内置的控件:Alert,Confirm等,但是这些控件通常根据浏览器产商的不同而形态各异,视觉效果往往达不到UI设计师的要求.更重要的是,这类内置控件的风格很难与形形色色的各种风格迥异的互联网产品的设计风格统一.因此,优秀的前端开发者们各自开发自己的个性化控件来替代浏览器内置的这些控件.当然,这类组件在网络上已经有不计其数相当优秀的,写这篇文章的目的不是为了说明我开发的这个组件有多优秀,也不是为了炫耀什么,只是希望通过这种方式,与更多的开发者互相交

【原创】如何管理你的 Javascript 代码

今天不聊技术的问题,咱们来聊聊在前端开发中如何管理好自己的 Javascript 代码.首先,咱们先来说说一般都有哪些管理方式?我相信 seajs.requirejs 对于前端开发者而言都不陌生,不错它们都是前端代码模块化开发的利器,显然以模块化的方式去管理我们的 Javascript 代码,是很不错的选择. 不过今天咱不谈模块化开发,因为上面的两个工具已经做得很好了,只要到他们的官方网站找到相应的文档资料,认真学习,不需太多时日你也能掌握模块化开发了.今天咱们要谈的是在不依赖模块管理工具的前提

【总结】IE和Firefox的Javascript兼容性总结

1.firefox不能对innerText支持. firefox支持innerHTML但却不支持innerText,它支持textContent来实现innerText,不过默认把多余的空格也保留了.如果不用textContent,如果字符串里面不包含HTML代码也可以用innerHTML代替. 2.禁止选取网页内容: 在IE中一般用js:obj.onselectstart=function(){return false;} 而firefox用CSS:-moz-user-select:none

【翻译】Zakas解答Baranovskiy的JavaScript测验题

原文:http://www.nczonline.net/blog/2010/01/26/answering-baranovskiys-javascript-quiz/ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

【BOOM】一款有趣的Javascript动画效果

实践出真知,有的时候看到一些有趣的现象就想着用自己所学的知识复现一下.    缘起 前几天在 github 上看到同事的一个这样的小项目,在 IOS 上实现了这样一个小动画效果,看上去蛮炫的,效果图: 我就寻思着,在浏览器环境下,用 Javascript 怎么实现呢? 在浓烈的好奇心驱使下,最终利用 Javascript 和 CSS3 完成了模仿上面的效果,通过调用方法,可以将页面上的图片一键爆炸,我给它起了个 boomJS 的名字,贴两张效果图:           实现 我感觉效果还是可以的