Function.create

Jake Verbaten raynos2 at gmail.com
Sat Sep 24 06:33:18 PDT 2011


There is no standardized way to create a new function with a prototype which
is not Function.prototype.

I propose Function.create

    /*
      Creates a new function whose prototype is proto.
      The function body is the same as the function fbody.
      The hash of propertydescriptors props is passed to defineproperties
just like
      Object.create does.
    */
    Function.create = (function() {
      var functionBody = function _getFunctionBody(f) {
        return f.toString().replace(/.+\{/, "").replace(/\}$/, "");
      };
      var letters = "abcdefghijklmnopqrstuvwxyz".split("");

      return function _create(proto, fbody, props) {
        var parameters = letters.slice(0, fbody.length);
        parameters.push(functionBody(fbody));
        var f = Function.apply(this, parameters);
        f.__proto__ = proto;
        Object.defineProperties(f, props);
        return f;
      };
    })();

This is the same as Object.create except the second parameter is a function.

It will create a new function whose function body is the same as the
function passed in.

I don't believe this is possible to do in ES5 without __proto__

jsfiddle showing an example. <http://jsfiddle.net/8CrqR/>

Related stackoverflow
question<http://stackoverflow.com/questions/7539148/how-do-i-inherit-functions>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110924/80db4262/attachment-0001.html>


More information about the es-discuss mailing list