gpt4 book ai didi

javascript - 全局变量的 JS 监听器?

转载 作者:行者123 更新时间:2023-11-30 06:06:55 25 4
gpt4 key购买 nike

我想将所有内容都包含在一个函数中,而不是将所有各种变量设为全局变量。

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

在此示例中,当索引更改时调用 doTheStuff()?或者我可能会以错误的方式解决这个问题?

var index = 0;


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

function one(){ two() }

function two(){ three() }

function three(){ }

function doTheStuff(){ }

}

最佳答案

可能有更好的方法来解决这个问题,例如:

// 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 在时间间隔之间改变不止一次;这是否重要取决于您要做什么。

展望 future ,您将能够使用属性上的 getter 和 setter 来执行此操作(新 ECMAScript 5 规范的一部分),但这仍未得到广泛实现。一些浏览器确实实现了它们,尽管使用它们自己的语法,但其他浏览器(还)没有。

关于javascript - 全局变量的 JS 监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com