Asleepace Asleepace - 5 months ago 30
Javascript Question

Javascript make variable a function that calls itself every time it's referenced

Hi I would like to know if it is possible to make a variable behave like this:

var someFlag = true;
var someWidth = (()=>(someFlag) ? 16 : 12)();

console.log(someWidth) // 16

someFlag = false;

console.log(someWidth) // would be nice if it was 12
// right now it still prints 16

Is something like this possible? Also I know that someWidth could be a function, the idea is I have a lot of code I would need to refactor so I don't want to do someWidth();

Answer Source

Great way to describe object property is here

var someFlag  = true;
Object.defineProperty(window, 'someWidth', {

  get:()=>someFlag ? 16 : 12

console.log(someWidth) // 16

someFlag = false;
console.log(someWidth) // 12

I dont think its good idea to have such global variables.You can try to create your own object maybe?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download