对象中的访问函数,嵌套在另一个函数中

acess function in objected, nested inside another function

我正在尝试管理一个连接实例,使用一个函数来处理空闲连接断开问题,使用 mysql 数据库和 node.js

目前,我有以下代码 (coffescript):

mysql = require 'mysql'

handleDisconnect = () ->
  connection = mysql.createConnection
    host: 'localhost'
    user: 'root'
    password: 'passroot'
    database: 'mydb'

  connection.connect (err) ->
    if err
      console.log 'Error connecting to db: ', err
    setTimeout handleDisconnect, 2000

  connection.on 'error', (err) ->
    console.log 'db error', err
    if err.code == 'PROTOCOL_CONNECTION_LOST'
      handleDisconnect()
    else
      throw err

  handleDisconnect.instance = connection

module.exports = handleDisconnect

express = require 'express'
router = express.Router()
connection = require('../database')().instance

bcrypt = require 'bcryptjs'

router.post '/', (req, res) ->
  credential = connection.escape req.body.credential
  password = connection.escape req.body.password
  res.send credential+password

module.exports = router

问题是,当我尝试访问路由时,出现以下错误:

无法读取未定义的 属性 'escape'

我做错了什么?

我认为您的问题是 handleDisconnect 的最后一行是 return 实例,因此您正试图从 instance 获取 instance,不是来自 handleDisconnect。所以如果你想访问它的属性,你将需要函数到 return 本身。

您还希望该函数使用 "this" 的等价物(coffeescript 中的 @)而不是具体引用 handleDisconnect.

示例代码:

mysql = require 'mysql'

handleDisconnect = () ->
  connection = mysql.createConnection
    host: 'localhost'
    user: 'root'
    password: 'passroot'
    database: 'mydb'

  connection.connect (err) ->
    if err
      console.log 'Error connecting to db: ', err
    setTimeout handleDisconnect, 2000

  connection.on 'error', (err) ->
    console.log 'db error', err
    if err.code == 'PROTOCOL_CONNECTION_LOST'
      handleDisconnect()
    else
      throw err

  @instance = connection
  @

module.exports = handleDisconnect

虽然我个人只会执行以下操作,但根本不用理会 "instance":

  1. 在你的函数中使用 @connection
  2. 报废 @instance = connection
  3. 获取函数return本身
  4. 使用require('../database')().connection访问它。