Search code examples
javascriptprototype

Preferred way of defining common fields in JavaScript: on prototype or constructor?


What is the preferred way of defining common fields for all instances of a class in Javascript? Via prototype or constructor?

function A() {
}

A.prototype.names = ['1', '2', '3']

Or

A.names = ['1', '2', '3']

I understand that these two ways require different access patterns, e.g., this.names and A.names, respectively.


Solution

  • They are similar ways. There will be only one copy of the names array.

    If you need it accessible without an instance, you should put it on the constructor since it will be easier for others to access: A.names instead of A.prototype.names.

    If you have a case where it will always be accessed by the instance, then you may put it on the prototype so callers can refer to this.names, but I'd suggest against that since it's not very intuitive.

    But it doesn't make a difference, it's just a matter of convenience when calling it.

    Having said that, my personal preference in these day of JS modules is to just export a separate const from the module. That way you don't need to prefix it with anything in the class itself and the callers and you can rename it when you import it if you wish. If you do it for private static variables, then you make them truly private.

    // A.js
    export class A () {}
    export const names = ["", "a"];
    // main.js
    import A, names as ANames from "a";
    console.log("look ma, no prefix for static fields", ANames);