可以为变量分配自调用函数模块,以便变量引用将触发在没有()运算符的情况下调用函数。我希望变量具有基于功能模块中代码的最新值。
代码可能是
count = 0
var x = function(){ return count }();
alert x; // should give 0
count = 7
alert x ; // should give 7
感谢
答案 0 :(得分:2)
可以使用Object.defineProperty
通过getter实现此行为,例如:
// Add a `somemethod` property to `window`
Object.defineProperty(window, 'somemethod', {
get: function() {
return Math.random();
}
});
console.log(window.somemethod);
console.log(window.somemethod); // Different value
答案 1 :(得分:1)
不,但您可以使用对象属性的getter和setter:https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters