After a long time I played around with plain JS again. And I'm struggling in fixing a closure problem.
Task: I'm using a function factory to set params for a returned function which I then want to call.
Problem: As far as I understand the params are passed by reference and when the execution context is popped off the stack, the variables lead to undefined memory space. How can I make this work?
function changeColorConstructor(greenLimit, redLimit) {
var greenLimit = greenLimit;
var redLimit = redLimit;
console.log('1. Green Limit in Constructor shell: ' + greenLimit);
return function(metric) {
var color;
console.log('3. Green Limit in returned function: ' + greenLimit);
switch(metric) {
case metric >= greenLimit:
console.log('Green');
color = '#56C621'; // green
break;
case metric < greenLimit && metric > redLimit:
console.log('Yellow');
color = '#F2E607'; // yellow
break;
case metric <= redLimit:
console.log('Red');
color = '#C64C20'; // red
break;
default:
color = '#C0C0C0'
break;
}
return color;
}
}
var indexColor = changeColorConstructor(5000, 10000);
console.log('2. Returned function: ' + indexColor);
console.log('4. Output from production function: ' + indexColor(5000));