nickcorin nickcorin - 1 year ago 56
Javascript Question

Sharing Variables between functions in ES6 Classes

I'm dabbling around with ES6 Syntax in Node.js. As a starting point I just tried creating a simple class that configures and returns an Express server - not sure if this would be good or not in production, though.

I'm having trouble with accessing the classes member variables in other functions. Take a look at the code below:

import express from 'express'
import http from 'http'

const _server = null
const _app = null

class HttpServer {

constructor (port) {
this._port = port;

if (this._app === null) {
this._app = express()
}

if (this._server === null) {
this._server = http.createServer(this._app)
}

return this._server
}

start (callback) {

this._server.listen(this._port, (error) => {
return callback(error)
})
}

}

export default HttpServer


The constructor seems to be working okay, although when I call the
start
method I get an error that the variable
this._server
is
undefined
. I thought the
this
keyword would be able to access the variables. I have tried replacing the
this
accessing method to using
HttpServer._server
but with no luck. Any tips or advice would be appreciated!

If I've made silly mistakes, please forgive me, I haven't hopped on the ES6 train before this!

Answer Source
  1. It is necessary to remove the check for null

  2. There is no need to return anything from constructor


class HttpServer {

    constructor (port) {
        this._port = port
        this._app = express()
        this._server = http.createServer(this._app)
    }

    start (callback) {
        this._server.listen(this._port, (error) => {
            return callback(error)
        })
    }

}