Making "super" work outside a literal?

Allen Wirfs-Brock allen at wirfs-brock.com
Fri Jun 24 03:23:37 PDT 2011


On Jun 24, 2011, at 6:47 AM, Brendan Eich wrote:

> On Jun 23, 2011, at 10:39 PM, Axel Rauschmayer wrote:
> 
>>>> Related topic: How would |super| be handled if |this| is lexical?
>>> 
>>> There's no connection, AFAIK. But we also don't have a lexical-this proposal in Harmony yet.
>> 
>> I would expect problems that are similar to that = this:
>> 
>> var obj = {
>>    mymethod: function(arr) {
>>        arr.forEach(function(x) {
>>            super.mymethod(x); // would this work?
>>        });
>>    }
>> }
> 
> From http://wiki.ecmascript.org/doku.php?id=harmony:object_initialiser_super :
> 
> PrimaryExpression : ...
> super 
> 
> The value of super is the same as the value of this but when super is used as the base of a property access the property lookup starts with the object that is the prototype of the object defined by the object literal that contains the reference to super.
> 
> This seems to say that the wrong |this| would be used, with the right property lookup starting point. Yikes.

Based upon these discussions, I would expect  the inner function to have an unbound super as it is not declaratively a method and has not be bound as a method using Object.defineMethod.  Note that in some earlier method I suggested that attempting to do a property lookup using an unbound this should throw.

The correct way to code the above would be:

var obj = {
   mymethod: function(arr) {
       let superMyMethod = super.myMethod;
       let self=this;
       arr.forEach(function(x) {
           superMyMethod.call.(self,x); 
       });
   }
}

Which is a pretty good demo of both the value of a lexically scoped this and why a lexically scoped super should parallel it.

> 
> 
>> Thankfully, I don’t think that super-calls will be very common in typical JavaScript code, in contrast to "this".
> 
> Not sure this will all pan out as proposed. 'super' in classes works. 'super' in any function nested however deeply in an object initialiser, perhaps not. If the above spec constrained the nesting to be immedate method of, that would seem to solve it. But would that be too restrictive?

People will need to learn that super has the same lexical scoping hazards as this and that to use super in a function it must be bound as a method

Allen

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110624/604a7a4f/attachment-0001.html>


More information about the es-discuss mailing list