2017-09-14 38 views
1

我正在嘗試使用Node和MySQL編寫JavaScript對象作爲購物任務的一部分。我想通過使它比函數式編程更具OOP來測試自己。我正在爲Transaction對象創建一個構造函數,其中包含所選項目的屬性,需要的數量和總成本。此外,將是顯示項目,選擇項目和購買項目的方法。用Node.js和MySQL查詢函數回調範圍確定

首先,我想要一個唯一的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

難道我有我的作用域全亂了?我如何解決範圍問題,以便我可以訪問「交易」對象的範圍?

讓我知道如果我的問題是不連貫的措辭......

+0

您使用的,如果有什麼驅動?我發現[Sequelize](http://sequelizejs.com)通常比低級別的MySQL驅動程序更好。 – tadman

回答

0

我相信這裏有兩個選項,你可以使用

arrow功能結合該到哪裏它被定義。

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