跟踪多个相同功能的运行,第2部分 [英] keeping track of multiple runs of the same function, part 2
问题描述
无论如何,我需要的是一些稍微不同的我需要一些方法这样做:
code> function run(arg){
this.ran = this.ran ||假;
if(!this.ran)init;
/ * code * /
this.ran = true;
}
这很好,我只是想确保这个代码工作即使
$ b
检查 //jsfiddle.net/GLh8u/1/rel =nofollow>这个出了我在说什么,第一个之后的所有调用都应该是真的,无论上下文
以充分利用闭包,我建议你包装你的主要功能在另一个启动ran标志的函数: p>
function initRun(){
var ran = ran ||假;
return function(arguments){
if(ran)
{
console.log(can not run any!
return;
}
ran = true;
console.log(i'm running!);
/ *你的逻辑在这里* /
}
}
var run = initRun();
那么你可以通过调用你的函数来测试它:
run();
run.call();
run.apply();
它成功运行一次,无论使用的调用方法。
迷你缺点是你需要一个额外的函数来封装你的初始运行函数,但我认为它更可靠和优雅,使用一个全局标志跟踪你的函数调用
Anyway what I need is actually something slightly different I need some way of doing this:
function run(arg) {
this.ran = this.ran || false;
if (!this.ran) init;
/* code */
this.ran = true;
}
This works fine, I just want to make sure that this code works even when this
in case it was called with call() or apply()
Check this out for what I'm talking about, All of the calls after the first one should all be true, no matter the context
to get full use of closures, i suggest you wrap your main function in another function that initiates the "ran" flag :
function initRun(){
var ran = ran || false;
return function(arguments){
if(ran)
{
console.log("can't run any more!");
return;
}
ran = true;
console.log("i'm running!");
/* your logic here */
}
}
var run = initRun();
then you can test it by calling your function in whatever way you want :
run();
run.call();
run.apply();
it successfully runs only once, no matter the calling method used.
The mini-downside is that you need an extra function that wraps your initial "run" function, but i think it's more reliable and elegant than to use a global flag that keeps track of your function calls
这篇关于跟踪多个相同功能的运行,第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!