Function.create

Tom Van Cutsem tomvc.be at gmail.com
Mon Sep 26 06:02:15 PDT 2011


For the record, function proxies could be used to implement a work-around.

There's a strawman to extend function proxies with support for custom
prototypes: <
http://wiki.ecmascript.org/doku.php?id=strawman:function_proxy_prototype>. I'm
not proposing this as a mechanism for function subclassing, simply as a
potential work-around until we have something better (such as the <|
operator).

In any case, this work-around would work only if the function's prototype
does eventually inherit from |Function.prototype|.

Cheers,
Tom

2011/9/24 Jake Verbaten <raynos2 at gmail.com>

> 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>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110926/beffb18c/attachment.html>


More information about the es-discuss mailing list