function.create

Function.create allows you to create named functions easily in JavaScript.

Polyfill for Function.create

This project provides a polyfill for the [currently discussed Function.create] in ECMAScript. This function allows you to create named functions easily.

Installing is as easy as:

npm install function.create

... or just download the Function.create.js file, which includes comments.

Loading it in Node.JS:

require('Function.create'); // the polyfill is installed globally 

Loading it in the browser:

<script src="Function.create.js"></script>

Two functions are provided:

  • Function.create(name, call[, construct[, proto]])
  • Function.getDisplayNameOf(f)

Currently the proto argument is not supported, but work is underway to support it in browsers where possible.

Example 1 (creating unnamed function):

var anon = Function.create(null, function(str) {
    console.log('anon called:', str);
});
 
anon('Hello, anon!');

Example 2 (creating simple named function):

var simple = Function.create('simple', function(str) {
    console.log('simple called:', str);
});
 
console.log(simple.name); // "simple" 
simple('Hello, simple!');

Example 3 (creating simple named constructor):

var Constr = Function.create('Constr', function(n) {
    this.= n;
});
Constr.prototype.say = function(text) {
    console.log('say: ' + text + '' + this.+ '!');
};
 
console.log(Constr.name); // "Constr" 
var c = new Constr('simple named constructor');
c.say('Bonjour'); // say: Bonjour, simple named constructor! 

Example 4 (creating named function and constructor):

var Person = Function.create('Person', function(name) {
    return new Person(name);
}, function(name) {
    this.name = name;
});
 
console.log(Person.name); // "Person" 
var p1 = new Person('Bobby');
var p2 = Person('Bobby');
console.log('Same person?', p1.name === p2.name); // true 

Example 5 (getting name of function):

var func = function fancyFunction() {};
console.log('Function name:', Function.getDisplayNameOf(func));

Hopefully, there is more to come!