There exists a use of arguments.callee with no good alternative?

314 views Asked by At

There is a lot of fallacies about arguments.callee and I'm trying to understand if exists use cases where it really can't be replaced by a viable ES5 strict mode alternative.

In the MDN arguments.callee documentation they point a use of arguments.callee with no good alternative with the following code example below:

function createPerson (sIdentity) {
    var oPerson = new Function("alert(arguments.callee.identity);");
    oPerson.identity = sIdentity;
    return oPerson;
}

var john = createPerson("John Smith");

john();

They inclusive linked a bug to show that in some cases, argument.callee can't be replaced by a code in conformance to ES5 strict mode.

But in understanding, the code they used as example can be replaced with the following strict mode alternative:

"use strict";

function createPerson(sIdentity) {
    var oPerson = function () {
        alert(oPerson.identity);
    };

    oPerson.identity = sIdentity;
    return oPerson;
}

var john = createPerson("John Smith");

john();

With that pointed, there really exists some algorithms where arguments.callee can't be replaced?

BOUNTY

To win the bounty I want the answer to contain a usage of arguments.callee where it will be much more obscure or impossible to use another solution.

In the MDN example, the version I wrote as an alternative doesn't change the usage of that piece of code.

3

There are 3 answers

3
Denys Séguret On BEST ANSWER

Here is a use case : keep a variable for an inlined event handler (which could come from a generated/templated code) without polluting the global namespace or the DOM or risking other name collisions :

<button onclick="var f=arguments.callee;alert(f.i=(f.i||0)+1)">CLICK</button>

Demonstration

Now, let's say it's not a legitimate use. Of course there's none really legitimate or arguments.callee wouldn't have been axed.

2
Scott Rippey On

When you create a function dynamically (from a string), it can't "capture" any outside variables, like a normal closure does.

So, the MDN example simulates the closure by making the value accessible via arguments.callee. There really is no other way without changing the signature of the function.

2
xlhuang On

I'm afraid you misunderstand the example. It means use the Function constructor there are not alternatives to argument.callee That's say, the code below

function createPerson (sIdentity) {
    var oPerson = new Function("alert(oPerson.identity);");
    oPerson.identity = sIdentity;
    return oPerson;
}

var john = createPerson("John Smith");

john();

is wrong