0

我正在使用一些执行此操作的代码:

var _init = false;

this.init = function(){

    if(_init)
        return;
    else
        _init = true;

    // Do a bunch of stuff here
}

在我看来,我想消除一个很小的竞争条件。函数的第二个实例可能在第一个实例设置为 trueinit之前开始运行。_init不太可能,但非零,是吗?

鉴于此,除了单例模式之外,是否有一种直接的方法可以消除这种竞争条件?

4

2 回答 2

4

javascript是单线程的(暂时忽略网络工作者)所以你应该没问题——不应该有竞争条件。

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

(function(){
    // init stuff here, but you don't need to have any of the _init stuff
})() // <-- this causes your function to be invoked immediately
于 2011-10-05T19:48:24.330 回答
0

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

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

    // now delete:
    delete this.init;
}

或者,如果您需要能够再次调用它,您可以将属性重新分配给无操作:

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

    this.init - function() {};
}

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

于 2011-10-05T19:59:57.623 回答