我制作了一个名为 Product 的函数,用于在 JavaScript 中创建对象。现在我有一个名为 setProduct 的函数,它从我的数据库 (websql) 中获取数据,并将数据库中的所有这些数据设置在当前对象中。这是我的代码:
function Product(nr, name, description, brand, category, price, tags, color, seccolor, image, sizes, db) {
this.nr = nr;
this.name = name;
this.description = description;
this.brand = brand;
this.category = category;
this.price = price;
this.tags = tags;
this.color = color;
this.seccolor = color;
this.image = image;
this.sizes = sizes;
this.db = db;
Product.prototype.setProduct = function(id, cb) {
var self = this;
var query = "SELECT * from products WHERE id='"+id+"';"
var res;
this.db.exec(query, function(results) {
res = results.rows.item(0);
self.nr = res.prod_nr;
self.description = res.prod_description;
self.brand = res.prod_brand;
self.category = res.prod_category;
self.price = res.prod_price;
self.tags = res.prod_tags;
self.color = res.prod_color;
self.seccolor = res.prod_sec_color;
self.image = res.prod_image;
self.sizes = res.available_sizes;
self.name = res.prod_name;
cb(true);
});
};
}
this.db = 我的数据库对象。setProduct 从该对象调用 exec 函数。就是这个代码:
Database.prototype.exec = function(query, cb) {
this.db.transaction(function(tx) {
tx.executeSql(query, [], function(tx, results) {
if (typeof(cb) == 'function') {
cb(results);
}
});
});
}
我尝试使用几个 console.logs 来查看数据丢失的位置,但我无法以某种方式找到它。
这是出错的地方:
$("div#home").off('click').on('click','li', function() {
var product = prod;
var prod_id = $(this).attr("id");
prod.setProduct(prod_id, function(a) {
if (a) {
console.log(prod.name); // console.log gives undefined
}
});
});
}