Minimalist Classes

Quildreen Motta quildreen at gmail.com
Wed Nov 2 07:57:24 PDT 2011


On 02/11/11 11:01, Erik Corry wrote:
> 2011/11/2 Axel Rauschmayer<axel at rauschma.de>:
>>> super Foo.bar(x) should desugar to Foo.prototype.bar.call(this, x)
>> http://wiki.ecmascript.org/doku.php?id=harmony:object_initialiser_super
>>
>> What is that you don’t like about Allen’s proposal? You are still hard-coding the name of the super-constructor (which is what `super` nicely avoids).
> "lookup starts with the object that is the prototype of the object
> defined by the object literal that contains the reference to super."
>
> So it only works inside an object literal, whereas mine is easier to
> understand and works anywhere.  If you are using it without any of the
> other stuff you can even trivially get your minifier to desugar for
> older browsers.
> I don't think hard coding the name of the super-constructor is a
> problem.
It is when you take into account that functions in JavaScript are not 
bound to an object, they are generic. You can simply assign any function 
to any object and it'll most likely just work.

So, what I mean is that, if you have `super' resolve to a hard-coded 
constructor name this is what you get (hell, I don't even use 
constructors anymore, those ugly, ugly things):

---
function Thing(name) {
   this.name = name
}
Thing.prototype.describe = function(){
   console.log('A thing ' + this.name)
}

function Subject(name) {
   super.constructor(name)
}
Subject.prototype = Object.create(Thing.prototype)
Subject.prototype.constructor = Subject
Subject.prototype.describe = function() {
   super.describe()
   console.log('A subject ' + this.name)
}

// For now, all is well, `super' in Subject will always resolve to Thing.
var car = new Subject('car')
car.describe()
// => 'A thing car'
// => 'A subject car'

// But remember that you can take any function and assign to any object
// Such that the following wouldn't work -- we want Teddy to be just
// a Subject here, not a Thing.
var teddy = { name: 'teddy', describe: Subject.describe }
teddy.describe()
// => 'A subject teddy'
// => 'A thing teddy'.


// Whereas with Allen's proposal, everything would work okay:
var teddy = { name: 'teddy' }

// The defineMethod call creates a new function `describe' that
// has its |super| reference bound to teddy's prototype
Object.defineMethod(teddy, 'describe', Subject.describe)

// And the new `describe' function can use this static |super| to
// determine where lookup starts
teddy.describe()
// => 'A subject teddy'
---

Of course, applying a function to another object is a different matter, 
which won't be solved by static super.


More information about the es-discuss mailing list