Skip to content

Instantly share code, notes, and snippets.

@spoike
Created June 25, 2014 12:20
Show Gist options
  • Select an option

  • Save spoike/7ad9c6ba6eff7b19ab8b to your computer and use it in GitHub Desktop.

Select an option

Save spoike/7ad9c6ba6eff7b19ab8b to your computer and use it in GitHub Desktop.
Super Simple Tutorial on How to Create a Functor in JavaScript
// 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;
}
// 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