Alternative to Function.bind

Juriy Zaytsev kangax at gmail.com
Thu Mar 26 22:15:41 PDT 2009


On Mar 22, 2009, at 11:11 PM, Igor Bukanov wrote:

> Various current proposals for Function.bind have a drawback that in a
> typical situation one needs to use the reference to the object twice
> as in
>
>  obj.method.bind(obj)
>
> This double-referencing can be avoided if bind would be applied to the
> object, not to the function. The result of the bind call would be a
> view of the object that translates any function property of the object
> into a bound function so obj.method.bind(obj) could be written as
>
>  obj.bind().method
>
> Even shorter form can be archived if bind would not be a function but
> rather a getter-property so the above can be written as
>
>  obj.bind.method
>
> With such short form the need, for example, for Array methods taking
> an extra thisObj argument would be pretty much removed.

This actually sounds like a great idea.
As a matter of fact, implementing this in ES3 seems quite trivial:

// Either with `Obejct.prototype.bind`

Object.prototype.bind = function(methodName) {
   var object = this;
   return function(){
     return object[methodName].apply(object, arguments);
   }
};

var o = {
   foo: function(){
     return this.bar;
   },
   bar: 'Boo'
};

o.bind('foo')(); // "Boo"

// or an alternative approach, which I like even more

Function.bind = function(object, methodName) {
   return function(){
     return object[methodName].apply(object, arguments);
   }
};

Function.bind(o, 'foo')(); // "Boo"

-- 
Juriy Zaytsev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20090327/98db489f/attachment.html>


More information about the Es-discuss mailing list