javascript - 将此传递给子函数
问题描述
这个函数应该从 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
给子函数,因为它现在返回 []?
(我基本上想要一个从数据库返回值的函数)
解决方案
有两种方法可以将“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
}
推荐阅读
- java - 如何使用 for(int i = 10; i >= 5; ++i) {
- go - Golang Lambda 函数确定来源
- python - 遍历字典并更新数据框值
- javascript - 需要帮助使用 Gatsby.js 实现 react-hook-form:表单甚至不会将值发布到控制台
- c# - connectionString 中的错误:不支持关键字:“数据源”C# MVC web.config
- javascript - JavaScript,订购对象的功能
- java - 防止在 Spring Boot api 中下载文件
- codeigniter - Codeigniter 重定向组中的所有路由
- c++ - 编写一个程序,使用内置函数和用户定义函数计算 sin(x) 的值
- javascript - MongoDB 通过元素编号修改对象字段的数组,无需 findAndModify 或更新查询