如何在不设置全局变量的情况下确定函数是否已被调用 [英] How to determine if a function has been called without setting global variable
问题描述
我正在寻找一种很好的技术来摆脱我想做的事情:设置全局变量.
I am looking for a good technique to get away from what I am tempted to do: to set a global variable.
第一次有人通过单击按钮来运行功能时,会触发一个初始功能,将一些东西变成可拖动对象.以后,如果他们第二次单击按钮,我想确定init
函数是否已初始化,如果不是,则不要再次调用它.我可以通过在init
函数中设置一个全局变量,然后从click函数中检查该变量来轻松地做到这一点,但是我想知道如何在不设置全局变量的情况下做到这一点.我真的很想举个例子.
The first time someone runs a function by clicking a button it triggers an initial function to turn a few things into draggables. Later, if they click the button a second time I want to determine if the init
function has been initialized, and if so to not call it again. I could easily do this by setting a global variable from the init
function and then checking that variable from the click function, but I'm wondering how to do this without setting a global variable. I would really like an example of a way to do this.
推荐答案
您可以向该函数添加属性:
You could add a property to the function:
function init() {
init.called = true;
}
init();
if(init.called) {
//stuff
}
这篇关于如何在不设置全局变量的情况下确定函数是否已被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!