Why are non-method properties in a prototype an anti-pattern?

Peter van der Zee ecma at qfox.nl
Wed Nov 7 13:27:40 PST 2012


On Wed, Nov 7, 2012 at 6:27 PM, Kevin Smith <khs4473 at gmail.com> wrote:
> This footgun:
>
>     function MyClass() {
>
>       this.value = 1;  // OK
>       this.list.push(0);  // Modifying the list for every instance -
> probably not intended.
>     }
>
>     MyClass.prototype.value = 0;
>     MyClass.prototype.list = [];
>

Thing is, this is not initialization. That would be setting it to null.

I do realize what you mean, and for new people it might look the same,
but it just is not.

I always explicitly declare all instance properties (method but also
non-method) in the prototype, never in the constructor. More often
than not, they won't even occur in the constructor if they're not used
there (yes, I know about jit class stuff, but in most apps it really
doesn't matter). Declaring them on the proto makes it easy to look-up
what instance properties an object/class might have and is a good
point for documentation (imo, better than doing so inside the
constructor).

And in that regard; not being able to specify them in a class
definition is an error (but I have no idea about the current state of
the proposal, so feel free to ignore this).

I know many people (here) don't use, or even are against, initializing
all instance properties on proto, but I still stand by it. Just my two
cents.

- peter


More information about the es-discuss mailing list