I'm using a cordova sqlite plugin. My question does not require you to have an understanding of the API. I'm not having any issues. I'm just a little uncertain about my understanding of the code below and how it works. I'm trying to have a much better understanding of the code I write.
So first, this variable "db" is defined as being a function (object) named "openDatabase" with parameters that the plugin understands and it's being called.
"db" which is actually a function (object) called "openDatabase" has a method called "transaction".
Am I doing alright so far?
Here's where I get a little confused: The db variable which is now equivalent to the openDatabase function has a method called transaction and it has a self invoking function as a parameter and the self invoking function has this variable "tx" as a parameter? Where does "tx" come from? Is it an object the "openDatabase" function returns after it's called? or is it not returned from "openDatabase" and it's just simply an object from the plugin? Is it always safe to assume variables as parameters that I haven't defined anywhere, that work, have been defined in the plugin, library or API I'm using? My last question is, why use a self invoking function as a parameter instead of a variable defined as that self invoking function? Any benefit? Thank you.
var db = openDatabase("DBTest", "1.0", "Sample Description", 200000);
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i < result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span> + item['text'] + '</span></li>';
}
});
Here's what's happening in that code, then I get to your specific questions:
db is being set to the return value from openDatabase. Then, the code calls db.transaction, passing in a callback function. The callback is called by db.transaction, which supplies the tx value, and in the callback we call tx.executeSql, passing in a second callback function. executeSql calls that second callback with the results, which code inside the second callback loops through.
Your questions:
So first, this variable "db" is defined as being a function (object) named "openDatabase" with parameters that the plugin understands and it's being called.
No. openDatabase is being called, and db is being set to its return value. That return value appears to be an object, but not a function (although it could be, there's no evidence that it is and it probably isn't).
"db" which is actually a function (object) called "openDatabase" has a method called "transaction".
Yes, except that db is probably not a function (although it could be), it's just an object.
The db variable which is now equivalent to the openDatabase function...
It isn't.
...has a method called transaction and it has a self invoking function as a parameter...
It's not self-invoking.
...and the self invoking function has this variable "tx" as a parameter? Where does "tx" come from?
Because the callback function isn't self-invoking, the tx argument's value comes from whoever calls the callback. The code in the transaction method will call the anonymous callback in that code. When it does, it will supply the value of the tx argument to that function. Similarly, the callback passed into executeSql will get called with values for tx and result.
Is it always safe to assume variables as parameters that I haven't defined anywhere...
Probably not. Instead, continue your study of JavaScript (you're clearly in the process of learning, which is great). You'll learn the syntax and be able to tell what's an argument, what's a variable, etc. Here's some info on that as comments:
var db = openDatabase("DBTest", "1.0", "Sample Description", 200000);
// ^^---- variable
db.transaction(function(tx) {
// Argument ------------^^
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
// Arguments ----------------------------------------------^^--^^^^^^
for (var i = 0, item = null; i < result.rows.length; i++) {
// Variables ----^------^^^^
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span>' +
item['text'] + '</span></li>';
}
});
});
Part of the confusion here seems to be with callbacks, so let's look at a much simpler version of callbacks, and one where we can see both sides of it.
Suppose something provides us a function, countUp, which we can give a start and end value to, and which will then call us with each value between:
countUp(0, 5, function(value) {
console.log(value);
});
And suppose when we use that, we get:
0
1
2
3
4
In our code above, we create but never call the callback we're passing to countUp. It's countUp's code that calls the callback. Here's what countUp might look like:
function countUp(start, end, callback) {
// ^^^^^^^^---- the callback argument
var i;
for (i = start; i < end; ++i) {
// vvvvvvvv------- calls our callback
callback(i);
// ^----- passing in this, which we get as `value`
}
}
Live Example:
function countUp(start, end, callback) {
var i;
for (i = start; i < end; ++i) {
callback(i);
}
}
countUp(0, 5, function(value) {
snippet.log(value);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
So first, this variable "db" is defined as being a function (object) named "openDatabase" with parameters that the plugin understands and it's being called.
No. The function stored in openDatabase is called and it's return value is assigned to db.
"db" which is actually a function (object) called "openDatabase" has a method called "transaction".
The value assigned to db is an object.
It might be a function, but there's no evidence in the code to suggest that it is.
It does have a method called transaction.
it has a self invoking function as a parameter
No, it doesn't.
foo( function () { } );
bar( function () { }() );
foo has a function as an argument.
bar has the return value of an immediately invoked function expression as an argument.
You can't have an IIFE as an argument itself because the IIFE resolves before the value is passed to the function.
transaction has a function passed as an argument.
Where does "tx" come from?
The transaction function (assuming the anonymous function doesn't get passed around some more first) will call the anonymous function. It will pass it arguments when it does.
Is it always safe to assume variables as parameters that I haven't defined anywhere, that work, have been defined in the plugin, library or API I'm using?
Yes
My last question is, why use a self invoking function as a parameter instead of a variable defined as that self invoking function?
If you mean Why use a function expression instead of a function stored in a variable? then it just saves the step of creating the variable and it keeps all the code together.
openDatabase is a funtion which returns an object that gets assigned to the db variable. This object has a method, transaction, which takes a function as an argument. When you call the transaction method, it sets up a transaction and then calls the function you pass it, with the newly-created transaction as its argument (the tx in your example). The function can now use the transaction to query the database. When it returns, the transaction method will do any necessary cleanup, and then return to the toplevel code.
This is too long for a comment yet doesn't directly answer the question. However, understanding this concept will hopefully allow you to answer all your questions yourself. Therefore I'm posting this as an answer.
Main concept: Functions are just objects just like numbers, strings etc.
You've probably seen code that looks like this:
var x = function (a) {...}
That is not a special syntax to declare functions. It is merely possible because functions are first class in javascript. First-class refers to things in the programming language that can be treated as data. In most languages numbers and arrays are first-class "things" (I'll avoid using the word "object" for now because it may have specific meanings in some languages, javascript included). In a lot of languages strings are also first-class things. In a few languages even functions are first class things.
Javascript is one language where functions are first-class: they can be treated as data
function x () {};
// you can assign them to variables:
var y = x;
y(); // call the function
// you can put them in arrays:
var a = [x,y];
a[0](); // call the function
// you can pass them as argument:
funtion b (foo) {
foo(); // call the function passed to b()
}
b(x); // this will cause b() to call x()
So when you see this:
db.transaction(function(tx) {/*...*/});
it's basically doing this:
function my_function (tx) {/*...*/}
db.transaction(my_function);
Therefore, you can sort of guess that db.transaction() looks something like this:
db.transaction = function (another_function) {
/* complicated processing ... */
another_function(result); // pass result variable to the function
// the user gave us.
}
So when you call:
db.transaction(function(tx) {/*...*/});
the function db.transaction() will call your function and pass it an argument (which you have defined as tx).
Think of tx as sort of the return value from db.transaction().
Related
Can someone please explain why we can simply pass a method name to a higher order function and everything works just fine. I know in something like Java I have to call the method words on each element individually. I was told that in Javascript if method signature matches we can simply pass in the name of the function with () and it will work. It is great but I want to know whats going on in the background. Why are we able to do this in javascript ?
function words(str) {
return str.split(" ");
}
var sentences = function(newArr){
return newArr.map(words);
}
In many languages you can pass a reference to a function as an argument to a function. That then allows the host function to use that argument and call that function when appropriate. That's all that is going on in Javascript. When you pass the name of a function without the () after it, you're just passing a reference to the function. That enables the host function to use that function as an argument and call it some time later.
In your specific example, .map() expects you to pass in a function that it will call once for each item in an array. So, you pass the name of a function that will then get called multiple times, once for each item in the array. That function you pass has a bit of a contract that it has to meet. It will be passed three arguments (value, index, array) and it must return a value that will be used to construct a new array.
In Javascript, since there is no argument type checking by the language, it is the developer's responsibility to make sure the arguments of the function you are passing match what the caller of that function will actually pass to it and you have to consult documentation of the calling code itself to know what arguments will be passed to it. You can name the arguments anything you want (that is entirely internal to your function implementation), but the order and the quantity of the arguments is determined by the caller and you must declare your function to match what the caller will provide.
Once thing that confused many in Javascript.
If you pass just a function name, you are passing a reference to the function (something that the host function can call at some later time).
array.map(myFn) // passes a function reference
Or, use an inline function (same outcome):
array.map(function(value, index, arr) {
// code goes here
})
If you put parens at the end of the function name, then the function is executed immediately and the return value of that function execution is what is passed:
array.push(myFn()); // pushes the result of calling myFn()
You are calling the words function repeatedly. You're calling it for each iteration of the map function.
The map function takes a callback which it runs for every iteration. That callback is usually in the form of
function (elementOfNewArr, indexOfNewArr, newArr) { }
Because functions are objects, you can store them on a variable and use that new variable name to call that function, instead of its original one. That's mostly the use of functions as objects. You can toss them around.
let foo = function () { return 'jasper!'; }
let boo = foo;
let ron = boo; // ron() will now return 'jasper!'
So, what you've done is plop in your callback function, though it was defined elsewhere. Since callback functions, like all functions are objects, you can declare that callback function, "saving" it to whatever variable you want and use it in anywhere that you can use it normally.
This is super useful if you have to use the same function in more than one place.
What I believe you are misunderstanding is that functions themselves can be treated the same as other variables in javascript. Consider this example:
var newArr = [1,2,3,4];
newArr.map(function(item){
return item * item;
});
In the above example, a function is passed as an argument to the map() function. Notice that it is described anonymously (no function name given). You can accomplish the exact same thing like this:
var newArr = [1,2,3,4];
function squared(item){
return item * item;
}
newArr.map(squared);
These two examples achieve the same thing, except in the second example, rather than writing the function in place, we define it earlier in the code. If it helps, you can even create the function in the same way as you would any other regular variable:
var squared = function(item){
return item * item;
};
You can pass this function around the same way. If you want to know the difference between defining functions in these ways try var functionName = function() {} vs function functionName() {}
I'm just trying to get a better understanding/confirmation of function arguments
In the function seen here:
function newFunction(data, status){
would the function apply specifically to data and status variables?
I don't quite understand how the arguments work.
Basic Scenario
When a function is defined, the () area is used for inputs. These inputs are mapped to what data is sent in.
function newFunction(data, status){
}
newFunction(1,2);
In this scenario, data will be assigned the value of 1, and status will be assigned the value of 2 for the scope of newFunction.
Missmatched inputs
However, it does not always directly map. If fewer arguments are sent, then the unassigned input variables become undefined.
function newFunction(data, status){
}
newFunction(1);
In this scenario, data will be assigned the value of 1, and status will be assigned the value of undefined for the scope of newFunction.
arguments object
Inside of the scope of newFunction, there is also access to the array like object called arguments.
function newFunction(data, status)
{
var args = arguments;
}
newFunction(1);
In this scenario, the variable args will hold the arguments object. There you can check args.length to see that only 1 argument was sent. args[0] will give you that argument value, being 1 in this case.
Function object
A function can be made into an object with the new keyword. By using the new keyword on a function, a Function object is made. Once the Function object is made, this may be used to refer to the current Function object instead of the global window.
function newFunction(data,status){
if( this instanceof newFunction ){
//use as a Function object
this.data = data;
}else{
//use as a normal function
}
}
var myNewFunction = new newFunction(1);
In this scenario, myNewFunction now holds a reference to a Function object, and can be accessed as an object through dot notation or indexing. myNewFunction["data"] and myNewFunction.data now both hold the value of 1.
This means that the function accepts both data and status parameters. The programmer calling the funciton (you) is required for providing the parameters when calling the function (also known as arguments.)
Let's look at a simplified example:
function add(x, y) {
return x + y;
}
The function here takes two numbers, adds them together, and returns the result. Now, as a programmer, you have the benefit of adding two numbers whenever you want without having to duplicate the functionality or copy/paste whenever you need your application to perform the same functionality.
Best of all, another programmer you work with can add two numbers together without worrying about how to do it, they can just call your function.
EDIT: Calling the function works as follows
var num1 = 10;
var num2 = 15;
var z = add(num1, num2); //z = 25
function newFunction(data, status){ ... function code ... }
This is the Javascript definition of a function called newFunction.
You can pass arguments to a function. These are variables, either numbers or strings, with which the function is supposed to do something.
Of course the function behaviour/output depends on the arguments you give it.
http://www.quirksmode.org/js/function.html
Below is the source code for a function that preloads images onto a page, the author has added in some comments to explain how the code works, but I still do not fully understand all of it. to be specific, He claims that the return value of this function is an empty object with a "done()" method that calls the predefined anonymous function, "postaction()". Is the user of this code supposed to enter his/her own code into the empty postaction function on line 2? If that's how it works, then what does "postaction=f || postaction" in the return object do?
Source code:
function preloadimages(arr){
var newimages=[], loadedimages=0
var postaction=function(){}
var arr=(typeof arr!="object")? [arr] : arr
function imageloadpost(){
loadedimages++
if (loadedimages==arr.length){
postaction(newimages) //call postaction and pass in newimages array as parameter
}
}
for (var i=0; i<arr.length; i++){
newimages[i]=new Image()
newimages[i].src=arr[i]
newimages[i].onload=function(){
imageloadpost()
}
newimages[i].onerror=function(){
imageloadpost()
}
}
return { //return blank object with done() method
done:function(f){
postaction=f || postaction
//remember user defined callback functions to be called when images load
}
}
}
link to author's page:http://www.javascriptkit.com/javatutors/preloadimagesplus.shtml
You can enter your own function for postaction, although it's not a callback function like you might expect.
However, it returns an object with a done function in it.
If you do soth. like
preloadimages().done(function () {
console.log('done')
});
your function will be executed. If you don't provide the fnction as a parameter of done, the default postaction will be called and do nothing, since it is an empty function
From reading that code, it looks like you're not meant to redefine postaction() - in fact, you shouldn't have to modify any of this code at all. You are actually expected to pass a function as an argument to the done() function, which will be called later on successful image load (a 'callback' function).
This line:
postaction=f || postaction
means "assign the value of f to postaction if f has a value, otherwise assign postaction to itself" (ie. don't change it).
I don't know what exactly this code is used for, but the returned object has a function done which can be used with or without function parameter.
Within done, this statement
f || postaction
Meaning f OR postaction returns f if f is not null/undefined or postaction else, so if you call
myreturnObject.done();
this evaluates to
postaction = postaction
because f is not define. If you call
myreturnObject.done(function(newImages) { ... });
this evaluates to
postaction = f.
Postaction is then used within the for loop in the imageLoadPost function. If you want some own coding there, you can pass it to the done method as parameter as shown. If you do not need any additional coding there, do not pass an function to postaction. The empty postaction function defined as fallback will be called then.
I have am trying to understand the Javascript/jQuery behind ColorBox. Some forms of syntax are a bit hard to search on Google as they are a bit lengthy to describe. I am having trouble understanding the following line:
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
So I assume a new function called publicMethod is being created, but how do we but I don't really understand anything beyond the first equals symbol ("=").
A normal function declaration would look like this:
function publicMethod(options, callback) {
So if anybody could help me understanding the syntax I would greatly appreciate it.
In:
$.fn[colorbox]
$ is an unhelpfully non-descriptive variable name. It contains an object.
$.fn access the fn property of that object.
fn[colorbox] accesses the property of that object which a name that matches the string stored in colorbox
But the right hand side of and = is defined first, So before it assigns that value to publicMethod it assigns the value of $[colorbox] to $.fn[colorbox].
… and before it does that it assigns (to there) a function.
function () {} defines an anonymous function and passes it left (so it gets stored in whatever is on the other side of =)
In JavaScript, functions are on the same level as other objects - you can assign them to variables, and pass them as parameters.
Normally, you would declare a function in this way:
function SomeFunc(arg1, arg2) { /* etc etc */ }
An equivalient way would to be:
var SomeFunc = function(arg1, arg2) { /* etc, etc */ }
...because, as above, functions themselves are values that may be assigned or passed.
Many libraries will accept functions as arguments to their own functions, running the passed function at a time which suits them (or passing them on elsewhere, a la any other variable). Often this is for callbacks. When passing functions as arguments, there isn't really a need to give them a name of their own, thus the following does the job:
SomeLibrary.doSomethingThenCallback(function(arg1, arg2) {
// the doSomethingThenCallback function will decide when, if ever,
// to run this, or pass it on somewhere else, or whatever else would
// be done with any other argument value.
});
This function publicMethod(options, callback) {} is nearly but not completely the same as var publicMethod = function(){options, callback}. In first case you create function named publicMethod and in the second you create anonymous function and assign it to publicMethod variable. Other to assignations just save this function for the further use as API method.
Man Im trying to understand callback functions. Ive been over many articles and posts here on SO. The explanations seem circular and I think Im actually getting farther from understanding lol. Ive used them apparently in javascript events, but its more a 'memorize these lines' than 'this is whats going on and why' sort of understanding.
So heres my understanding.
Say you have 2 objects, function p() and function k(). You pass function k to p(). p() can then access k's inner variables.
function p(x){
alert(x.n);//5
}
function k(){
this.n = 5;
}
p(k);
Embarrassing how long its taken me to get just this.
Maybe an example will help?
// First, lets declare the function we're going to call
calledFunction = function (callback, arg) {
callback(arg);
};
// Second, lets declare the callback function
callbackFunction = function (arg) {
alert(arg);
};
// Next, lets do a function call!
calledFunction(callbackFunction, "HAI");
So, calledFunction()'s callback argument is callbackFunction but, if you notice, we aren't calling the function yet, we're passing a variable the contains the function, and its arg function is just something to alert(). When calledFunction() is executed it takes whatever was passed as the callback argument and calls it with arg as its first, and only, argument.
Helped?
Edit: This still works if you use function foo() {}-style declarations. (just in case; I don't know how fluent you are with JavaScript)
You are doing it wrong. this.n = 5; in k() does not set its "inner variable", and x.n access the function object's x property, instead of its inner variable.
Try this:
function p(x) { alert(new x().n); }
Variable binding is an important programming concept.
I think this article helps. http://www.hunlock.com/blogs/Functional_Javascript