Making "super" work outside a literal?

Axel Rauschmayer axel at rauschma.de
Sun Jun 19 11:43:14 PDT 2011


Note that "this" always points to where the search for a method starts (the “receiver” of the method call), there (current) beginning of the prototype chain. "here" points to where a method has been found. This is a static aspect, except that turning it into a property of a function would make it impossible to put the same function into multiple objects.

>> Then
>>        super.foo(x, y)
>> would desugar to
>>        Object.getPrototypeOf(here).foo.call(this, x, y)
>> 
>> With call() and apply(), you would have here === this.
> 
> When the prototype chain is three or more objects long, I'm wondering
> what would happen.
> 
> With "here" I'd expect and think people would expect the following
> behavior (but I don't think it is what your proposal of "here" would
> do.)
> 
> function Alpha() {}
> Alpha.prototype.one = function() {return 'Alpha.one';};
> Alpha.prototype.two = function() {return 'Alpha.two';};
> Alpha.prototype.three = function() {return super.one() + ' ' +
> here.one() + ' ' + this.one();};
> 
> function Beta() {}
> Beta.prototype = Object.create(Alpha.prototype);
> Beta.prototype.one = function() {return 'Beta.one';};
> Beta.prototype.two = function() {return super.one() + ' ' + here.one()
> + ' ' + this.one();};
> 
> function Gamma() {}
> Gamma.prototype = Object.create(Beta.prototype);
> Gamma.prototype.three = function() {return super.one() + ' ' +
> here.one() + ' ' + this.one();};
> 
> var a = new Alpha();
> var b = new Beta();
> var g = new Gamma();

Wow, quite a puzzle. I hope I get it right:

> a.three(); // "Alpha.one Alpha.one Alpha.one"

super.one() would cause an exception, because method "three" is found in Alpha.prototype (=> becomes "here") whose prototype is Object.prototype, which does not have a method one().

> b.two(); // "Alpha.one Beta.one Beta.one"

Would work. The search for super.one() would start in Alpha.prototype, the search for here.one() would start in Beta.prototype, the search four this.one() would also start in Beta.prototype.

> g.two(); // "Alpha.one Beta.one Gamma.one"

Is OK, only "this" is different, "here" is still Beta.prototype.

> g.three(); // "Beta.one Gamma.one Gamma.one"


I dont’t see "Gamma.one" anywhere.

I would say: "Beta.one Beta.one Beta.one"

Maybe you can condense this into a simpler example that gets to the core of where you think things might be tricky.

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list