此功能用于报告和增加每个特定障碍物的总数(计数器)。
function warningMaker( obstacle ){
var count = 0;
return function ( number, location ) {
count++;
alert("Beware! There have been " +
obstacle +
" sightings in the Cove today!\n" +
number +
" " +
obstacle +
"(s) spotted at the " +
location +
"!\nThis is Alert #" + count + " today for " + obstacle + " danger."
);
};
}
现在如果我通过说例如
来调用该函数warningMaker("obstacleName1")(2,"locationName"); ===counter 1
warningMaker("obstacleName1")(2,"locationName"); ===counter still 1
但如果我这样称呼它,
var obstacle1Maker = warningMaker("obstacleName1");
var obstacle2Maker = warningMaker("obstacleName2");
obstacle1Maker(2,"MiddleEarth");
obstacle1Maker(2,"Hogwarts");
obstacle2Maker(3,"Narnia");
答案 0 :(得分:0)
两个不同的闭包装有两个不同的计数器。你想要这样:
var obstacles={};
function warningMaker( obstacle ){
var obstacles[obstacle] = obstacles[obstacle]||0;
return function ( number, location ) {
obstacles[obstacle]++;
alert("Beware! There have been " +
obstacle +
" sightings in the Cove today!\n" +
number +
" " +
obstacle +
"(s) spotted at the " +
location +
"!\nThis is Alert #" + obstacles[obstacle] + " today for " + obstacle + " danger."
);
};
}
我将所有计数存储在全局对象中。因此它不依赖于封闭等......
为什么您的代码无法正常工作:
warningMaker("obstacleName1");
这组装了一个新的函数上下文(function + closure)。将函数移出其范围(变量周围)时会发生这种情况。该函数仍然可以访问它,因为它绑定到它们(称为闭包)。因此,如果你再调用两次,你将创建两个不同的上下文,其中包含两个不同的 count 变量......