keeping track of multiple runs of the same function, part 2
This is related to this
Anyway what I need is actually something slightly differ开发者_JS百科ent 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
you can replace "this" by "arguments.callee". arguments.callee should always give you the object representing your current function thus isolating you from changing "this". (However I did not test^^)
When you define a free-standing function, "this" refers to the global window object. When that is the case, you might as well just use the global variable explicitly to avoid any chance of "this" from being usurped from .apply() or .call()... provided that is the desired behavior.
function run(arg) {
window.ran = window.ran || false;
if (!window.ran) init();
/* code */
window.ran = true;
}
As a side note, if you define a function as a property of an object, "this" refers to the owning object. Note that "this" is a reference to a function's owner, and the owner depends on the context.
EDIT: also, as a followup to @Anurag's suggestion, is this unsuitable?
var run = (function createRun() {
var ran = false;
return function(arg) {
if (!ran) init;
// code
ran = true;
};
})();
run(arg);
精彩评论