Class double-bind

Jason Orendorff jason.orendorff at gmail.com
Mon Mar 2 23:14:54 UTC 2015


On Mon, Mar 2, 2015 at 4:15 PM, Allen Wirfs-Brock <allen at wirfs-brock.com> wrote:
> and conversely if we have something like this:
>
> class Bar {
>    constructor(n) {this.n=n}
>    static get const() {return 42);
>    op(x) { return new Bar(Bar.const )}
> };
>
> the inner workings of the class would get very screwed up if somebody did:
>         Bar = { };

...But that would just be a bug in the program. The same thing would
happen if you overwrote any function or method anywhere with a random
object. For `new Bar` to stop working at that point is what people
will *expect*, and I don't think we do programmers any favors by
mysteriously masking certain kinds of bug for a little while.

My example was something useful, something programmers will do on
purpose, that goes silently wonky because of the double binding.

> the chain of logic I apply for arriving at the specified behavior is:
>
> 1) There are many reasons a developer may want to refer to a class from
> within it's body and the obvious way of doing so should be reliable and
> tamper-proof.

The reliability benefit is surely offset somewhat by how confusing this is.

If we wanted classes to be tamper-proof, then the outer binding would
be immutable as well. It's not; it's mutable; yet every use case I can
think of for actually assigning to it is silently broken due to the
double binding.

I favor keeping it mutable, because that's useful and JS is the sort
of language where you're allowed to hack some things. But as long as
it's mutable there should not also be a second implicit binding seen
by different code. One declaration creating two bindings + mutability
= hall of mirrors.

> 2) This behavior of function declarations is actually quite astonishing and
> if we had a do over on FunctionDeclaration we would probably give it a local
> name binding just like function expressions (we might fight about it a
> while, but I'm pretty sure that's where we would end up).

That's precisely what I thought, until I started thinking about what
it'll actually be like to use this feature as a programmer.

To me, this issue explains why functions are the way they are.

> 3) Class declarations already differ from function declarations in a number
> of other ways, so class declaration consistency with function declaration on
> this one arguably buggy behavior is not a particularly strong position.

Sure, if it were purely about matching what functions do for the sake
of matchiness, I wouldn't be here.

-j


More information about the es-discuss mailing list