keeping track of multiple runs of the same function, part 2

╄→гoц情女王★ 提交于 2019-12-12 02:34:39

问题


This is related to this

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


回答1:


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:


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^^)




回答3:


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);


来源:https://stackoverflow.com/questions/4895283/keeping-track-of-multiple-runs-of-the-same-function-part-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!