我创建了一个简单的问题示例
函数计数应该计算从查询中收到的项目数。然而,我正在实现它的方式,当我从路线呼叫时,我失去了对我的功能的引用。在这种情况下,函数doWork来自另一个我无法修改的节点模块。
无论如何都要绕过这个
function Counter(){
this.array = createArray();
};
Counter.prototype.count = function (q){
query(q, function(data){
if(data === "tabe")
{
this.array[0].total++;
}
else
if(data === "chair")
{
this.array[1].total++;
}
else
if(data === "lamp")
{
this.array[2].total++;
}
});
};
createArray = function (){
var array = [];
array.push({item : "table",
total: 0});
array.push({item : "chair",
total: 0});
array.push({item : "lamp",
total: 0});
return array;
};
//The query function is actually in another node module that I cannot edit
query = function( data, callback){
callback(data);
}
module.exports = Counter;
index.js文件
/* Process query */
router.get('/submit', function(req, res, next) {
var counter = new Counter();
counter.count("table");
counter.count("table");
counter.count("lamp");
for(var i = 0; i < counter.array.length; i++){
console.log(counter.array[i]);
}
res.end();
});
答案 0 :(得分:1)
这是因为回调方法的执行上下文没有引用Counter
实例,您可以使用Function.bind()将自定义上下文传递给回调方法。
Counter.prototype.count = function (q) {
query(q, function (data) {
if (data === "tabe") {
this.array[0].total++;
} else if (data === "chair") {
this.array[1].total++;
} else if (data === "lamp") {
this.array[2].total++;
}
}.bind(this));
};
另一种选择是使用闭包变量
Counter.prototype.count = function (q) {
var self = this;
query(q, function (data) {
if (data === "tabe") {
self.array[0].total++;
} else if (data === "chair") {
self.array[1].total++;
} else if (data === "lamp") {
self.array[2].total++;
}
});
};