我正在测试 node.js 中的回调机制,以查看触发回调的上下文。在运行以下代码时,我注意到一个奇怪的行为,我想知道你是否能解释一下:
var outID =2;
var closure = function (){
var that = {};
that.id = 1;
outID = 3; //if line is commented out outID will always be 2.
that.inside = function(cb){
console.log("level 0");
console.log("thatID:" +that.id);
console.log("outID:" +outID);
setTimeout(function(){
console.log("level 1");
console.log("thatID:" +that.id);
console.log("outID:" +outID);
setTimeout(function(){
setTimeout(cb,0,that.id);
},0);
}, 0);
};
return that;
};
var level3 = function(id){
console.log("level 100S");
console.log("id " + id);
console.log(outID); // --- Interesting value is 3.
};
var cl = new closure();
cl.inside(level3);
输出是:
node: no process found
level 0
thatID:1
outID:3
level 1
thatID:1
outID:3
level 100S
id 1
3
[Finished in 0.1s]
为什么最后一个值是 3 而不是 2 ?