在方法中失去对对象的引用
Lose refernce to object within method
>我为我的问题创建了一个简单的例子
函数计数应计算我从查询中收到的项目数。但是,我目前实现它的方式在从路由调用时丢失了对我的函数的引用。 在这种情况下,函数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;
索引.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();
});
这是因为回调方法的执行上下文不引用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++;
}
});
};
相关文章:
- 如何使用object.assign()从其他对象引用基本对象属性
- 返回 JavaScript 类值而不是对象引用
- Facebook:当发布期望对象引用时显示打开的图形对话框
- Javascript-如何从字符串/对象引用回调
- 将其用于对象引用
- 如何将对象引用传递到 mootools 中另一个对象的构造函数中
- Javascript:将类/对象引用设置为 NULL,内存中的子对象/类会发生什么
- 在 Jquery 中,我可以存储对象引用并在以后使用它吗?
- 将对象函数传递给请求动画帧时丢失对象引用
- JavaScript ecma6中的对象引用
- 在JSON中存储对象引用
- 为什么可以在内部函数成员中访问对象引用,而不能在内部属性成员中访问
- 对象引用的隐式传递是如何工作的
- 按对象的 ID 删除对选定对象的对象引用
- 在调用的函数中使用对象引用(this)
- 如何在testcomplete+js中获取对象引用
- 在Angularjs服务中为返回对象引用的http请求提供的数据构建简单的缓存
- JavaScript对象引用
- 对象引用未设置为行中的对象的实例,如果 (!string.IsNullOrEmpty(tdcd.文本)&&
- 如何在使用声明式 Dojo 时获取对象引用