Super Simple Tutorial on How to Create a Functor in JavaScript
// Test case:
var $ = createFunctor();
$();
// outputs 'Hello World'
$.setName('Magic Mike');
$();
// outputs 'Hello Magic Mike'
// 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;
}