0

I want to write a generic way to change properties inside a function. It actually happens inside a function, but I think the problem can be simplified in the following way.

var showItemA = true;
var showItemB = true;
var showItemC = false;

var switchToggle = function (toggleTarget) {
    toggleTarget = !toggleTarget
    // Do other stuff
    console.log(toggleTarget);
    //false
};

switchToggle(showItemA);
console.log(showItemA);
//true; but I want it to be false

I am well aware of this earlier question, but I need it to be generic to handle different properties. Is there a way to throw outside variables or properties at a function and have it change their value?

Community
  • 1
  • 1
Roy Prins
  • 2,790
  • 2
  • 28
  • 47

2 Answers2

1

Can you use an object? This is essentially the same as using window as in your found answer, but doesn't unnecessarily pollute the global space with loads of new variables.

var obj = {};
var key = 'showItemA';
obj[key] = true;

var switchToggle = function (toggleTarget) {
    obj[toggleTarget] = !obj[toggleTarget];
    console.log(obj[toggleTarget]);
    // false
};

switchToggle(key);
console.log(obj[key]);
// false

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
0

Found an answer here:

Passing a global variable to a function

The trick is not to pass the value, but rather the reference to the variable to the function. Makes sense.

Community
  • 1
  • 1
Roy Prins
  • 2,790
  • 2
  • 28
  • 47