Posted 10 June 2012 - 04:35 PM
Thanks for your comments, and great questions!!
1. An API is an Application Programming Interface, and it just means that if you write some software that can be used by another piece of software, the API is what specifies how to do it.
When you use the built-in JavaScript functions, you're using an API, because you are using functions running in the browser (a program) that are designed to be used by other programs (your JavaScript program). We often call collections of functions that work together to achieve some purpose--like Geolocation--an API, as in "The Geolocation API". And all that means is there is some documentation somewhere (in this case, the HTML5 spec) that tells you *how* to use those Geolocation functions.
Does that make sense?
2. When you write getCurrentPosition(displayLocation, displayError) , you are not calling the displayLocation and displayError functions, you are passing them as values! I know it seems odd to pass a function as a value, but that is actually one of the powerful things about JavaScript (not all programming languages allow you to do this!). Think of the parameters displayLocation and displayError as names for values, just like any other parameter that expects a value (whether thats a number, a string, an object, or a function!). Because getCurrentPosition() is a function in JavaScript, rather than one you write yourself, you don't see getCurrentPosition() actually calling those functions. If you could see inside getCurrentPosition(), you'd see it call one of the functions, say displayLocation() and of course it would be passing in your position (as an object).
You can write your own functions that take other functions as arguments. For example:
function f(g) {
return g(1);
}
function add1(x) {
return x + 1;
}
f(add1);
You'll get 2. Kind of mind-bendy, right? So what's happening here is that you are creating two functions: add1 takes a number, x, and adds 1 to it and returns it. Function f takes a function, which you give the name g. f calls g, and passes a number, 1, into it.
So, when you pass the function value add1 to f, f uses the parameter name g as the name for the function *value* (remember, JavaScript is pass by value!!) and calls g, with the result that you get the number 2.
I hope that makes sense and helps clear things up a bit. The function/value/passing a function to another function is a very complex topic that deserve a more in-depth treatment for sure, and we just didn't have room in HF HTML5 Programming to delve into it.
Elisabeth
Elisabeth Robson
Co-founder, WickedlySmart.com
Author: Head First HTML5 Programming, Head First HTML and CSS, Head First Design Patterns