Created
August 30, 2012 14:44
-
-
Save jpetto/3529912 to your computer and use it in GitHub Desktop.
JavaScript functions - first class objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Functions are first class objects, which means you can: | |
- store them in a variable | |
- store them in an array | |
- pass them as an argument to a function | |
- return them from a function | |
*/ | |
// store a function in a variable | |
var smart_play = function(num) { | |
return num * 2; | |
}; | |
console.log(smart_play); | |
// store a variable containing a function in an array | |
var my_stuff = ['indecision', 'grapes', smart_play, 42]; | |
console.log(my_stuff); | |
// store another function in a variable | |
// this function accepts a function as its second parameter | |
// and returns a function | |
var gamble = function(num, gamble_function) { | |
// powerful stuff going on here! | |
var result = gamble_function(num); | |
return function(name) { | |
alert("Hello " + name + ". You started out with " + num + " and ended up with " + result + "."); | |
}; | |
}; | |
// pass in the function by name | |
var my_gamble = gamble(10, smart_play); | |
my_gamble("Teddy KGB"); | |
console.log(my_gamble); | |
// pass in the function from its array position | |
var my_gamble2 = gamble(15, my_stuff[2]); | |
my_gamble2("Mike McDermott"); | |
console.log(my_gamble2); | |
// why are these different? they look the same, right? | |
console.log(my_gamble === my_gamble2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment