我在测试node.js中的回调机制以查看引发回调的上下文。在运行下面的代码,我注意到一个奇怪的行为,我不知道你能不能解释一下: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?
为什么当你将它设置为3时,在你调用的构造函数中它的值应该是2 ? – JohnnyHK
是的,我明白这是因为我写的。我只是不知道在运行timeOut时node.js如何知道这些值(符号?)? – qballer