Счетчик в замыкании
by Евгений
HTML
<input type="button" id="button" value="button" />
<div id="res">images/scene1.jpg</div>
JavaScript
document.getElementById('button').onclick = (function() {
var count = 1;
return function() {
if (++count > 3) count = 1;
document.getElementById('res').innerHTML = 'images' + count + '.jpg';
};
})();
// еще один счетчик
var callback = (function(i){
return function(a){
i++;
return a + i;
};
})(0);
var str = "This is the house that Jack built. This is the malt That lay in the house that Jack built. This is the rat, That ate the malt That lay in the house that Jack built";
console.log(str.replace(/Jack/g, callback));
// или даже так
console.log(
"This is the house that Jack built. This is the malt That lay in the house that Jack built. This is the rat, That ate the malt That lay in the house that Jack built".replace(
/Jack/g,
(function(i){
return function(a){
i++;
return a + i;
};
})(0)
)
);