Javascript Node.js和MySQL查询函数回调的作用域
我正在尝试使用Node和MySQL编写一个JavaScript对象,作为购物任务的一部分。我想通过让它更面向对象而不是函数式编程来测试自己。我正在为事务对象创建一个构造函数,该对象具有所选项目、所需数量和总成本的属性。此外,还有显示项目、选择项目和购买项目的方法 首先,我还希望有一个唯一的ItemID数组,用于验证用户是否选择了有效的产品。我遇到了一个作用域问题,如果在对象的作用域中定义,则此.ids[]未定义。我下面的解决方案是在本地定义它,并将该数组作为参数传递,以避免作用域。这个解决方案也不允许我访问事务对象的作用域变量Javascript Node.js和MySQL查询函数回调的作用域,javascript,mysql,node.js,Javascript,Mysql,Node.js,我正在尝试使用Node和MySQL编写一个JavaScript对象,作为购物任务的一部分。我想通过让它更面向对象而不是函数式编程来测试自己。我正在为事务对象创建一个构造函数,该对象具有所选项目、所需数量和总成本的属性。此外,还有显示项目、选择项目和购买项目的方法 首先,我还希望有一个唯一的ItemID数组,用于验证用户是否选择了有效的产品。我遇到了一个作用域问题,如果在对象的作用域中定义,则此.ids[]未定义。我下面的解决方案是在本地定义它,并将该数组作为参数传递,以避免作用域。这个解决方案也
this.listProducts = function(connection) {
connection.query("SELECT * FROM products WHERE stock_quantity>0", function(err,res) {
if (err) throw err;
this.ids = [];
for (var i = 0; i < res.length; i++) {
this.ids.push(res[i].item_id);
console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
}
// res.forEach(function (element) {
// console.log("this.ids=",this.ids);
// this.ids.push(element.item_id);
// console.log(element.item_id + " " + element.product_name + " " + element.price);
// });
connection.end();
console.log(this.totalCost, this.ids);
});
};
我得到TypeError:connection.query(…)。调用不是函数
我的范围都搞砸了吗?如何解决作用域问题,以便访问“Transaction”对象的作用域
如果我的问题措词不连贯,请告诉我。我相信这里有两个选项可以使用
新函数将此绑定到定义它的任何位置
this.listProducts = function(connection) {
var that = this;
connection.query("SELECT * FROM products WHERE stock_quantity>0",
//use arrow instead of anonymous function
(err,res) => {
if (err) throw err;
this.ids = [];
for (var i = 0; i < res.length; i++) {
this.ids.push(res[i].item_id);
console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
}
connection.end();
console.log(this.totalCost, this.ids);
});
}
this.listProducts=函数(连接){
var=这个;
connection.query(“从库存数量>0的产品中选择*”,
//使用箭头代替匿名函数
(err,res)=>{
如果(错误)抛出错误;
this.ids=[];
对于(变量i=0;i
或者将此引用存储为
this.listProducts = function(connection) {
var that = this;
connection.query("SELECT * FROM products WHERE stock_quantity>0", function(err,res) {
if (err) throw err;
that.ids = [];
for (var i = 0; i < res.length; i++) {
that.ids.push(res[i].item_id);
console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
}
connection.end();
console.log(that.totalCost, that.ids);
});
}
this.listProducts=函数(连接){
var=这个;
连接.查询(“从库存数量>0的产品中选择*”,函数(err,res){
如果(错误)抛出错误;
即:ids=[];
对于(变量i=0;i
如果有,您使用的是什么驱动程序?我发现,一般来说,它比使用低级MySQL驱动程序要好得多。
this.listProducts = function(connection) {
var that = this;
connection.query("SELECT * FROM products WHERE stock_quantity>0", function(err,res) {
if (err) throw err;
that.ids = [];
for (var i = 0; i < res.length; i++) {
that.ids.push(res[i].item_id);
console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
}
connection.end();
console.log(that.totalCost, that.ids);
});
}