Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
防止函数在JavaScript中多次运行_Javascript_Singleton Methods - Fatal编程技术网

防止函数在JavaScript中多次运行

防止函数在JavaScript中多次运行,javascript,singleton-methods,Javascript,Singleton Methods,我正在使用一些代码来实现这一点: var _init = false; this.init = function(){ if(_init) return; else _init = true; // Do a bunch of stuff here } 在我看来,那里有一个很小的种族条件,我想消除它。init函数的第二个实例可以在第一个实例将\u init设置为true之前开始运行。不太可能,但不是零,是吗 考虑到这一点,有没有一种

我正在使用一些代码来实现这一点:

var _init = false;

this.init = function(){

    if(_init)
        return;
    else
        _init = true;

    // Do a bunch of stuff here
}
在我看来,那里有一个很小的种族条件,我想消除它。
init
函数的第二个实例可以在第一个实例将
\u init
设置为true之前开始运行。不太可能,但不是零,是吗


考虑到这一点,有没有一种简单的方法来消除这种竞争条件,而不是像单线程模式这样的竞争条件呢?

javascript是单线程的(暂时忽略web workers),所以您应该没问题——不应该有竞争条件

然而,我认为这样做的“标准”方法是使用自调用函数

(function(){
    // init stuff here, but you don't need to have any of the _init stuff
})() // <-- this causes your function to be invoked immediately
(函数(){
//这里有init元素,但你不需要任何init元素

})()//javascript是单线程的(暂时忽略web工作人员),所以您应该没问题——应该没有竞争条件

然而,我认为这样做的“标准”方法是使用自调用函数

(function(){
    // init stuff here, but you don't need to have any of the _init stuff
})() // <-- this causes your function to be invoked immediately
(函数(){
//这里有init元素,但你不需要任何init元素

})()//确保函数只运行一次的一种简单方法是在末尾删除该方法:

this.init = function(){
    // Do a bunch of stuff here

    // now delete:
    delete this.init;
}
或者,如果需要再次调用该属性,则可以将其重新分配给no op:

this.init = function(){
    // Do a bunch of stuff here

    this.init - function() {};
}

但这只能确保每个实例只运行一次函数-如果您需要它只运行一次,那么基于标志的方法可能更好,正如其他海报所建议的,对于单线程代码,您对争用条件的担忧是毫无根据的。

确保函数只运行一次的一种简单方法是在末尾删除该方法:

this.init = function(){
    // Do a bunch of stuff here

    // now delete:
    delete this.init;
}
或者,如果需要再次调用该属性,则可以将其重新分配给no op:

this.init = function(){
    // Do a bunch of stuff here

    this.init - function() {};
}

但这只能确保每个实例只运行一次函数-如果您需要它只运行一次,那么您基于标志的方法可能更好,而且正如其他海报所建议的,您对竞争条件的担忧对于单线程代码来说是没有根据的。

因为javascript是单线程的,在任何给定时间只有一个执行线程,因此在测试
\u init
变量时没有其他线程可以调用函数。由于javascript是单线程的,因此在任何给定时间只有一个执行线程,因此在测试
\u init
变量时没有其他线程可以调用函数。