class sugar

Peter Michaux petermichaux at gmail.com
Sat Jun 4 06:11:25 PDT 2011


On Sat, Jun 4, 2011 at 12:04 AM, Mark S. Miller <erights at google.com> wrote:

> Hi Peter, your memory is correct and the classes design has had a tortuous
> history responding to many pressures. As you see from my rewrite of your two
> examples above, the design we ended up promoting to harmony can express
> both.

Thanks for those examples.

> While I agree that the objects-as-closure approach is more elegant, it
> is less common. Most class-like code today is expressed in the
> prototype/this-based style.

Yes that is true and I think I know why it is less popular.

When a programmers new to ECMAScript want to make a class, they look
in JavaScript books for language support for making classes. They find
that the language gives them the new/prototype/this machinery. They
then struggle mapping their ideas of classes from C++, Java, etc onto
the new/prototype/this machinery because they think that in order to
be able to do object-oriented programming the language must provide
machinery specific to that task. Since the job of these books is to
explain the language, it appears that new/prototype/this are the way
to do OOP in ECMAScript.

What these programmers don't know is that books like SICP and
JavaScript: The Good Parts show that the language has at least one
other way to do the whole OOP business.

So new/prototype/this win popularity by default because the books are
obligated to spend space explaining them. The new/prototype/this-style
isn't winning in the popularity race based on merit in all or perhaps
even most cases.

For example, I had a new programmer join my team a several months ago.
He expressed skepticism when I said we don't use "new", "prototype",
or "this" but he was willing to play along. After a couple months, he
told me that he had changed his mind and thought the closure-based
system was more natural in JavaScript.


> Personally, for new code that does not need to interoperate with old
> prototype/this-based code and does not need to be super high performance, I
> will always use the objects-as-closures pattern.

It is the same for me.

----

Thanks for you're detailed response, Mark.

Peter


More information about the es-discuss mailing list