Created
June 25, 2014 12:20
-
-
Save spoike/7ad9c6ba6eff7b19ab8b to your computer and use it in GitHub Desktop.
Super Simple Tutorial on How to Create a Functor in JavaScript
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
| // Here is a quick tutorial on how to create a functor, an object that acts | |
| // both as function and an object of functions (e.g. much like jQuery's globally | |
| // available $ object) | |
| // This is a factory method that creates the functor for us: | |
| function createFunctor() { | |
| // Declared variables are scoped within the createFunctor function | |
| // so they are practically private: | |
| var name = 'World'; | |
| // The functor is just an ordinary function, and is fairly simple to create: | |
| var functor = function() { | |
| console.log('Hello ' + name); | |
| }; | |
| // The functor is also a Javascript Object, meaning you can attach functions | |
| // to it like this: | |
| functor.setName = function(newName) { | |
| name = newName; | |
| }; | |
| // Return the functor | |
| return functor; | |
| } |
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
| // Test case: | |
| var $ = createFunctor(); | |
| $(); | |
| // outputs 'Hello World' | |
| $.setName('Magic Mike'); | |
| $(); | |
| // outputs 'Hello Magic Mike' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment