使用Node.js和MySQL查询函数callback来确定范围

我正在尝试使用Node和MySQL编写JavaScript对象作为购物任务的一部分。 我想通过使它比function性编程更多的OOP来testing自己。 我正在创build一个交易对象的构造函数,其中包含所选项目的属性,数量和总成本。 此外,将是显示项目,select项目和购买项目的方法。

开始时,我想也有一个唯一的itemID数组,这将是用户select一个有效的产品的validation。 我有一个范围问题,如果在对象的作用域中定义this.ids []是未定义的。 我的解决scheme将在本地定义它,并将该数组作为parameter passing,以避免范围界定。 这个解决scheme也不会允许我访问Transaction对象的作用域variables。

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); }); }; 

我尝试过了

  .... console.log(this.totalCost, this.ids); }); }.call(this); 

我得到TypeError: connection.query(...).call is not a function

我有我的范围所有搞砸了吗? 我如何解决范围问题,以便我可以访问“交易”对象的范围?

让我知道,如果我的问题不是连贯一致的…

我相信在这里有两个select可以使用

新的箭头函数将其绑定到任何定义的地方。

 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 = 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); }); }