Alternative to Function.bind

Mark S. Miller erights at google.com
Fri Mar 27 09:17:16 PDT 2009


On Thu, Mar 26, 2009 at 11:01 PM, Erik Arvidsson
<erik.arvidsson at gmail.com> wrote:
> Here is one way to implement object.bind.method using ES3.1

Hi Erik, this is a really cool example! A few minor nits...


> Object.defineProperty(Object.prototype, 'bind', {
>  enumerable: false,
>  writable: false,

For a getter/setter property as you're defining here, there is no
writeable: attribute. Rather, the right way to make it read-only is

    set: undefined,

>  configurable: false,
>  get: function() {
>    var rv = {};
>    // this would need to use Object.getOwnPropertyNames and
>    // recursively check Object.getPrototypeOf
>    for (var key in this) {
>      if (typeof this[key] == 'function') {
>        rv[key] = this[key].bind(this);
>      }
>    }
>    Object.freeze(rv);
>    Object.seal(rv);
>    Object.preventExtensions(rv);

freeze() implies seal() and preventExtensions(), so these last two
lines are harmless but not needed.

>    return rv;
>  }
> });
>
> This does not create proxies for getters or setters nor values. It
> does seal, freeze and prevent extensions on the bind proxy so that it
> is clearer that it is not the object itself that you are operating on.
> Another option is to replace all the "methods" on the object with the
> bound methods.
>
> Anyway, this is just an example of the power of the ES3.1 meta programming.


-- 
    Cheers,
    --MarkM


More information about the Es-discuss mailing list