首页 > 解决方案 > 将此传递给子函数

问题描述

这个函数应该从 MySQL 数据库中获取一些数据:

function getXXX() {
  this.output = []
  con.connect(function(err) {
    if (err) throw err
    con.query('SELECT * FROM `XXX`', function(err, result) {
      if (err) throw err
      this.output = result
    })
  })
  return this.output
}
console.log(getXXX())

我如何传递this给子函数,因为它现在返回 []?

(我基本上想要一个从数据库返回值的函数)

标签: javascriptmysql

解决方案


有两种方法可以将“this”传递给内部函数

//Use arrow function that stores "this" automatically

function getXXX() {
    this.output = []
    con.connect((err) => {
        if (err) throw err
        con.query('SELECT * FROM `XXX`', function (err, result) {
            if (err) throw err
            this.output = result
        })
    })
    return this.output
}

//Bind "this" with .bind function

function getXXX() {
    this.output = []
    con.connect((function (err) {
        if (err) throw err
        con.query('SELECT * FROM `XXX`', function (err, result) {
            if (err) throw err
            this.output = result
        })
    }).bind(this))
    return this.output
}

推荐阅读