This might be unusual to developers that never thought about that, but in JS a function is also an object. You can pass a function around as an argument to another function just like you can pass a string, for example. This is extensively used and very handy.
Take a look at this example. We will pass functions to another function that will use them.
var myDog = {
bark: function(){
alert('Woof!');
}
};
var myCat = {
meow: function(){
alert('I am a lazy cat. I will not meow for you.');
}
};
function annoyThePet(petFunction){
//let's see what the pet can do
petFunction();
}
//annoy the dog:
annoyThePet(myDog.bark);
//annoy the cat:
annoyThePet(myCat.meow);
Note that we pass myDog.bark and myCat.meow without appending parenthesis “()” to them. If we did that we would not be passing the function, rather we would be calling the method and passing the return value, undefined in both cases here.
If you want to make my lazy cat start barking, you can easily do this:
myCat.meow = myDog.bark; myCat.meow(); //alerts 'Woof!'