Automatically binding extracted methods

Andrea Giammarchi andrea.giammarchi at gmail.com
Fri Jun 14 11:46:03 PDT 2013


I think that's possible since "the beginning of the time" ... we just need
to be a bit more pragmatic with what's available.

Examples here:
http://webreflection.blogspot.com/2012/11/my-name-is-bound-method-bound.html

summarized as

```javascript
Generic.prototype.bound = function (methodName) {
  var boundName = '__secret' + methodName;
  return this[boundName] || (this[boundName] = this[methodName].bind(this));
};
```

What I'd love to see is a Function.prototype.bindOnce though, with a
private WeakMap able to do something like:
```javascript
var wm = new WeakMap; Function.prototype.bindOnce = function (context) {
return wm.has(context || (context = null)) ? wm.get(context) :
wm.set(context, this.bind(context)), wm.get(context); };

// example
obj.method.bindOnce(obj);
```

or, even better, an `Objectprototype.boundTo` method such:

```javascript
Object.defineProperty( Object.prototype, 'boundTo', { value: (function(wm){
return function boundTo(method) { var mirror = wm.get(this) ||
(wm.set(this, { m: [], // collection of method pointers b: [] // collection
of bound methods }), wm.get(this)), i = mirror.m.indexOf(method); if (i <
0) { i = mirror.m.push(method) - 1; mirror.b.push(method.bind(this)); }
return mirror.b[i]; }; }(new WeakMap)) } ); // example
obj.boundTo(obj.method); obj.boundTo(genericCallback);
```
Done internally would surely perform faster.

Cheers




On Fri, Jun 14, 2013 at 3:45 AM, Axel Rauschmayer <axel at rauschma.de> wrote:

> Thanks to proxies now having a separate trap for “invoke”, we can
> automatically bind methods on “get”. I’ve written down my thoughts here:
> http://www.2ality.com/2013/06/auto-binding.html
>
> Axel
>
> --
> Dr. Axel Rauschmayer
> axel at rauschma.de
>
> home: rauschma.de
> twitter: twitter.com/rauschma
> blog: 2ality.com
>
>
> _______________________________________________
> 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/20130614/e0ec6193/attachment-0001.html>


More information about the es-discuss mailing list