Javascript使变量成为每次被引用时都会自行调用的函数 [英] Javascript make variable a function that calls itself every time it's referenced
本文介绍了Javascript使变量成为每次被引用时都会自行调用的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以使变量的行为如下:
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
像这样可能吗?我也知道someWidth可能是一个函数,想法是我有很多代码需要重构,所以我不想做someWidth();
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();
推荐答案
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?
这篇关于Javascript使变量成为每次被引用时都会自行调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文