我正在尝试使用 Node 和 MySQL 编写一个 JavaScript 对象作为购物任务的一部分。我想通过让它比函数式编程更面向对象来测试自己。我正在为一个交易对象创建一个构造函数,该对象具有所选项目、所需数量和总成本的属性。此外,还有显示项目、选择项目和购买项目的方法。
一开始,我还想拥有一组唯一的 itemID,以验证用户选择了有效的产品。我有一个范围界定问题,如果在对象的范围内定义,则 this.ids[] 是未定义的。我下面的解决方案是在本地定义它并将该数组作为参数传递以避免范围界定。该解决方案也不允许我访问 Transaction 对象的作用域变量。
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
我的范围界定是否一团糟?如何解决范围问题,以便我可以访问“事务”对象的范围?
如果我的问题措辞不连贯,请告诉我...
最佳答案
我相信这里有两个选项可供您使用
新arrow将 this 绑定(bind)到定义它的任何地方的函数。
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引用
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);
});
}
关于javascript - 使用 Node.js 和 MySQL 查询函数回调的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225219/