我试着理解javascript闭包,拉我的头发。我正密切关注this example.我的实际代码是在node.js中,但我不认为这是一个主要问题(错误代码除外)。
这是我精简的代码:
var jsonsymbols = {
"id5": "WFC",
"id4": "AMZN",
"id3": "BABA",
"id2": "YHOO",
"id1": "GOOG",
"id0": "AAPL"
};
// assume an unknown number of stock symbols..
var count = 0;
var outputPrices = {};
for (key in jsonsymbols) {
outputPrices['newid' + count]['price'] = get_price(jsonsymbols[key], count, function() {
console.log(" Dummy function"); // callback function is used when looking up only one stock.
});
count++;
}
console.log("\ncount = " + count);
console.log("\noutput = " + JSON.stringify(outputPrices));
function get_price(symbol, countindex, callback) {
setInterval(function() {
// do nothing... The actual function makes a http call to another server
// and does stock price lookup. We can only look up one stock at a time,
// hence the repeated calls.
}, 1000);
return 124.12;
callback();
};

(嗯。我是这个片段内容的新手。我还创建了jsfiddle)当前的错误代码是Uncaught TypeError: Cannot set property 'price' of undefined
我显然错过了一些愚蠢的东西。有没有办法让我的蛋糕和啤酒喝?我正在学习这种异步的东西是如何工作的,遗憾的是我在纯粹的抽象概念中开始学习过程非常困难。我需要一个具体的例子来开始,从中我可以推断回到摘要。
以前有人来过这里吗?为什么这不起作用? THX。