On Apr 2, 2012, at 9:47 PM, Brendan Eich wrote:
> Douglas Crockford wrote:
>> 
>> 
>> It seems I misunderstood what we were agreeing to. I think the (this...) 
>> form is critically important, and the immutability thing as well.
> 
> (...)
> 
> I agree that leading |this| could be important for dynamic non-method 
> use-cases, but those are relatively rare (let's not discount JQuery, but 
> again, it could use long functions and survive). We could put 
> leading-this-parameterization on the agenda for May, but we'll have to be 
> careful not to lose consensus on arrows.

I was chatting this evening with a friend about this (ruby) thing:

class Numeric
  (Math.methods - Module.methods - ["hypot", "ldexp"]).each do |method|
    define_method method do
      Math.send method, self
    end
  end
end


And I showed him how one could do that easily in JavaScript:

Object.getOwnPropertyNames(Math).forEach(function (key) {
  if (typeof Math[key] === 'function') {
    Number.prototype[key]= function () {
      return Math[key](this);
    };
  }
});


Then I thought, let's see how would that look like with arrows ?


Object.getOwnPropertyNames(Math).forEach((key) => {
  if (typeof Math[key] === 'function') Number.prototype[key]= () => 
Math[key](this);
});

And it turns out that here, the outer/enclosing context `this` isn't the one 
you want/need. You'd need a dynamically bound `this` instead:

Object.getOwnPropertyNames(Math).forEach((key) => {
  if (typeof Math[key] === 'function') Number.prototype[key]= (this) => 
Math[key](this);
});

and thus the this-in-the-parameters-list trick.

I don't think it's such a rare case: Inside a constructor function called with 
`new`, yes, `this` is most likely going to be the right `this` always, but when 
you are building objects with a factory (e.g. with a .create() method), the 
enclosing `this` usually isn't going to be the right one.
-- 
Jorge.
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to