【发布时间】:2017-03-27 22:35:40
【问题描述】:
我正在研究 Node.js 中的 ES6 语法。作为一个起点,我只是尝试创建一个简单的类来配置和返回一个 Express 服务器 - 但不确定这在生产中是否好用。
我在访问其他函数中的类成员变量时遇到问题。看看下面的代码:
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
构造函数似乎工作正常,尽管当我调用start 方法时,我收到一个错误,即变量this._server 是undefined。我认为this 关键字可以访问变量。我尝试将this 访问方法替换为使用HttpServer._server,但没有运气。任何提示或建议将不胜感激!
如果我犯了愚蠢的错误,请原谅我,在此之前我没有跳上 ES6 火车!
【问题讨论】:
-
那是因为您正在检查
this._app是否为null- 这将失败,因为它不为空,它是undefined,就像this._server。你永远不会创建express的实例。此外,您不需要在构造函数中进行这些检查,只需创建this._app = express()和this._server = http.createServer(this._app); -
啊,好吧,这确实有道理。我如何将它们都设置为
null,就像我尝试使用const globals一样? -
在构造函数中,您可以使用
this._app = null;将它们初始化为null。 -
我在
start中删除了空检查和我登录typeof端口、应用程序和服务器。我得到undefined、function和object。不再设置端口。
标签: javascript node.js express ecmascript-6