function cambiarPropiedades(elemento){
if(typeof control === "undefined"){
control = true; //No puedo usar el operador var
}
if(control == true){
//Código a ejecutar
control = false;
} else {
//Otro código a ejecutar
control = true;
}
}
var
I can't use the define operator control
because the code doesn't work because it creates a local scope variable, and therefore every time the function executes and dies, the variable and its value die with it, so it would always go into the primer if
and the result would always be the same. I remember that when I gave some basic brushstrokes in PHP they explained to me and I tinkered a bit with the operator static
, which allowed me to define a variable that is not destroyed when the function dies.
Is there a way to do something equivalent? In the example you can see that I have chosen to declare the variable control
as a global variable but I would like it not to be so, to avoid problems and out of pure curiosity. I'm also not convinced to call it _control to indicate its local scope and differentiate it. It's possible?
Try using function cache or memoization . Like everything in object javascript, you can add a property to the functions in execution and use them as cache :
So then you have a variable that is not dereferenced when the function execution is finished and is non-global.