Justin
Justin

Reputation: 45410

Define static class properties in JavaScript

What is the best practice way to define static class private properties in JavaScript ES6 in Node.js?

I have the following Log class:

'use strict';

const moment = require('moment');
const LOG_DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ';

module.exports = class {
    static debug(txt) {
        console.log(`${moment().utc().format(LOG_DATE_FORMAT)} [debug] ${txt}`);
    }

    static info(txt) {
        console.info(`${moment().utc().format(LOG_DATE_FORMAT)} [info] ${txt}`);
    }

    static warn(txt) {
        console.warn(`${moment().utc().format(LOG_DATE_FORMAT)} [warn] ${txt}`);
    }

    static error(txt) {
        console.error(`${moment().utc().format(LOG_DATE_FORMAT)} [error] ${txt}`);
    }
};

Is defining moment and DATE_FORMAT outside of the module.exports and thus class definition the correct way of doing this?

Upvotes: 2

Views: 1492

Answers (1)

jfriend00
jfriend00

Reputation: 708116

Yes, it's an acceptable way of doing things. Since you want to define some variables that you share among all your static methods, you have basically four choices:

  1. Define them as statics on the class also so you can reference them using the class name as a prefix. This has the benefit or drawback (depending upon what you want) that it makes them publicly accessible on your exported class.

  2. Define them as module level variables as you've done. This makes them accessible by all the static methods, but keeps their use private to your module.

  3. Redefine them separately inside of each method.

  4. Define them as globals.

Option #3 seems like a lot of repetition and certainly wouldn't be very DRY.

Option #4 does not seem like a good way to go since there's no reason to make these globals (you pretty much never want to use globals with node.js anyway).

So, it comes down to option #1 or #2 and which to choose totally depends upon whether you want their values to be accessible outside the module or not. If you want them exported also, then make them static properties on your class and refer to them with the class prefix. If you only want to use them inside the module, then what you have done is perfect.

Upvotes: 2

Related Questions