Function.create
This allows you to create named functions easily in JavaScript. Tested browsers:
- IE 8
- Chrome
- Firefox
- Safari
It is similar to the sketched Function.create
in ECMAScript (two years old). The proposal was never accepted, so this function is not based on any standards, but it's still very useful.
Getting Started
Download:
- Development Version (16kb, Uncompressed with Plentiful Comments)
- Production Version (4kb, Minified and Gzipped)
- Production Version without Unicode support (1kb, Minified and Gzipped)
Installing:
npm install function.create
Loading it in Node.JS:
; // now loaded globally
Loading it in the browser:
Usage
Two functions are provided:
- Function.create(name, call[, construct[, proto]])
- Function.getDisplayNameOf(f)
The proto
argument sets the prototype of the newly created function. This is available in all browsers except MSIE, where it is simulated by copying the whole prototype chain.
Example 1 (creating unnamed function):
var anon = Function; ;
Example 2 (creating simple named function):
var simple = Function; console; // "simple";
Example 3 (creating simple named constructor):
var Constr = Function;Constrprototype { console;}; console; // "Constr"var c = 'simple named constructor';c; // say: Bonjour, simple named constructor!
Example 4 (creating named function and constructor):
var Person = Function; console; // "Person"var p1 = 'Bobby';var p2 = ;console; // true
Example 5 (getting name of function):
var {};console;
Example 6 (named classes):
{ var Class = Function; Classprototype = properties; Classprototypeconstructor = Class; return Class;} var Person = ;var andy = 'Andy';console; // trueconsole; // "Andy"
Example 7 (functor, or the story about function inheriting object):
{ return Function;} {}Moduleprototype = ;Moduleprototypeconstructor = Module; Moduleprototype { console;};Moduleprototype { this; return a + b;}; var M = ;console; // "Module"console; // "function"console; // true, in all browsers except MSIE; // outputs "I want to say: 20 + 22 = 42"