简体   繁体   中英

referring to the current function without using its name/arguments.callee

I have done a fair amount of research but have not been able to find any answers, to what seems like a simple question:

I want to associate a property with a function (to use as a static variable in this function), like so:

function foo() {
    if (!foo.counter) {
        foo.counter = 1;
    }
    else {
        foo.counter++
    }
    // rest of the function code goes here...
}

If I change the name of the function later, I don't want to have to change references to it inside function definition. So, is there a way to refer to the currently executing function? (other than arguments.callee which is now deprecated). A keyword like thisFunction ?

If not, what is the reason for not having something like this?

I do not know of an identifier or keyword like thisFunction (besides arguments.callee ) that JavaScript exposes, but one way to achieve the same effect is to name the function foo in a closure, and return foo from that closure. That way you can always use the name foo within foo to refer to itself, regardless of what variable it's assigned to by your program:

var fn = (function() {
  function foo() {

     if (!foo.counter) {
        foo.counter = 1;
    }
    else {
        foo.counter++
    }
    // rest of the function code goes here...
  }

  return foo;
})();
function foo() {
  if (typeof foo.counter=="undefined") {
    foo.counter = 1;
  }
  else {
    foo.counter++
  }
  return foo;
}

var x = new foo();
alert(x.counter);  //1
var y = new foo();
alert(x.counter); //2

If you don't need to refer to the counter outside of the function, this will work. Instead of setting a variable of the function itself, you define a variable outside of the function and let the function modify that instead. Every time you call makeFoo , it makes a new variable x and returns a function using x . Every time you call the returned function, it still refers to the same x created by makeFoo . Additionally, this entirely encapsulates the variable, ensuring that almost nothing outside of the returned function can change it (it definitely won't be changed by most things outside of the returned function, but there is enough funky javascript reflection that I can't guarantee that nothing will change it). Certainly, moving the function between variables won't affect the counter (ie x=makeFoo();y=x;x=null; ).

function makeFoo() {
  var x=0;
  return function () {
    x++;
    return x;
  }
}

//different counters
x=makeFoo();
y=makeFoo();
x();//returns 1
y();//returns 1
x();//returns 2
y();//returns 2

//same counter
x=makeFoo();
y=x;
x();//returns 1
y();//returns 2
x();//returns 3
y();//returns 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM