理解callback function in javascript

以下内容主要摘自[1,2]

(1)In javascript, functions are first-class objects, which means functions can be used in a first-class manner like objects, since they are in fact objects themselves: They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions”。

(2)Callback functions are derived from a programming paradigm called functional programming. At a simple and fundamental level, functional programming is the use of functions as arguments. Functional programming was—and still is, though to a much lesser extent today—seen as an esoteric technique of specially trained, master programmers.

(3)When we pass a callback function as an argument to another function, we are only passing the function definition. 

(4)If callback function is a asynchronous function[自己定义的callback函数如果调用了异步函数库,则该函数是一个异步函数;否则,同步函数.例如:node中读取文件的两个函数 fs.readfile() vs fs.readfileSync()], then callback function will be executed later than those code behind the function which called the callback function.

(5)every function in JavaScript has two methods: Call and Apply.

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.

Reference

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

[2]http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/?WPACFallback=1&WPACRandom=1413199645166

时间: 2024-12-20 20:09:51

理解callback function in javascript的相关文章

(C/C++) Callback Function

原文: http://www.codeguru.com/cpp/cpp/cpp_mfc/callbacks/article.php/c10557/Callback-Functions-Tutorial.htm Callback Functions Tutorial Introduction If you are reading this article, you probably wonder what callback functions are. This article explains

【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 th

sample callback function

1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 2 "http://www.w3.org/TR/html4/loose.dtd"> 3 <html> 4 <head> 5 <title>callbackTest</title> 6 7 <script type="text/javascript">

C语言中的回调函数(Callback Function)

1 定义和使用场合 回调函数是指 使用者自己定义一个函数,实现这个函数的程序内容,然后把这个函数(入口地址)作为参数传入别人(或系统)的函数中,由别人(或系统)的函数在运行时来调用的函数.函数是你实现的,但由别人(或系统)的函数在运行时通过参数传递的方式调用,这就是所谓的回调函数.简单来说,就是由别人的函数运行期间来回调你实现的函数. 这一设计允许了底层代码调用在高层定义的子程序(如图1-1所示).C语言中回调函数主要通过函数指针的方式实现. 图1-1 回调函数在软件系统的调用结果 回调的用途十

Dreamweaver 扩展开发: Calling a C++ function from JavaScript

After you understand how C-level extensibility works in Dreamweaver and its dependency on certain data types and functions, it’s useful to know how to build a library and call a function. The following example requires the following five files, locat

Callback Function

typedef void (*callbackFun)(int a, int b);struct exm { int type; callbackFun fun;}; A pointer is a special kind of variable that holds the address of another variable. The same concept applies to function pointers, except that instead of pointing to

Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net

Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net 原文地址:https://www.cnblogs.com/chucklu/p/11159211.html

IT忍者神龟之理解回顾面向对象的 JavaScript

JavaScript 函数式脚本语言特性以及其看似随意的编写风格,导致长期以来人们对这一门语言的误解,即认为 JavaScript 不是一门面向对象的语言,或者只是部分具备一些面向对象的特征.本文将回归面向对象本意,从对语言感悟的角度阐述为什么 JavaScript 是一门彻底的面向对象的语言,以及如何正确地使用这一特性. 适合阅读人群 当今 JavaScript 大行其道,各种应用对其依赖日深.web 程序员已逐渐习惯使用各种优秀的 JavaScript 框架快速开发 Web 应用,从而忽略了

bind原理 附带上自己的一些理解 (引自javascript设计模式和与看法实践)

Function.prototype.bind = function(){ //this指向的是所有由Function构造器产生的函数 var self = this, // 保存原函数 //[]就相当于Array.prototype,(借用Array构造器原型上的shift方法将传递的第一个参数拿出来作为this指向的对象) context = [].shift.call( arguments ), // 需要绑定的 this 上下文 //slice作用就是返回选定的数组元素(这里[].sli