2010-09-28 654 views
2

我想将所有内容都包含在一个单一的函数中,而不是让所有的变量全局化。全局变量的JS监听器?

是否可以在函数main中设置一个事件监听器来观察全局变量?

在这个例子中调用doTheStuff()时索引被改变了吗?或者我可能会以这种错误的方式去做?

var index = 0; 


function main(data, data, data, data, data, data,) 
{ 

function one(){ two() } 

function two(){ three() } 

function three(){ } 

function doTheStuff(){ } 

} 

回答

1

有可能是一个更好的方式去了解这一点,例如:

// An anonymous function to provide scoping 
(function() { 
    var index = 0; // A non-global, but accessible to everything within this scoping function 

    function setIndex(newIndex) { 
     index = newIndex; 
     doTheStuff(); 
    } 

    function one() { two(); } 

    function two() { three(); } 

    function three() { 
     // Perhaps `three` needs to change the index 
     setIndex(index + 1); 
    } 

    function doTheStuff() { } 
})(); 

如果你想要做什么,不为工作,你可以设置一个间隔定时器根据保存的副本检查值。

var index = 0; 
function main(...) { 
    var lastIndex = index; 

    setInterval(checkIndex, 100); // Every 100ms or so 

    function checkIndex() { 

     if (index != lastIndex) { 
      lastIndex = index; 
      doTheStuff(); 
     } 
    } 

    // Other functions omitted... 

} 

这将是可能的index比间隔之间被修改一次以上;无论这个问题是否取决于你想要做什么。未来,您将可以通过属性(新ECMAScript 5规范的一部分)上的getter和setter来做到这一点,但这仍未得到广泛实施。有些浏览器确实实现了它们,尽管它们有自己的语法,但其他浏览器还没有。

0

如果你不拥有index你不能用跨浏览器的方式。如果您拥有index,您可以使用get/set函数来处理其值。

或者如果你不需要跨浏览器工作,你可以在Firefox,Safari 3 +,Opera 9.5中使用Getters and Setters