Search code examples
javascriptfunctionself-reference

Replace arguments.callee inside of new Function


Some string is converted into function by new Function(...) call.

How can I get referent to this function inside of the string without using arguments.callee?

var f = new Function('return arguments.callee.smth');
f.smth = 128;
f(); // 128

Solution

  • The only way to do such thing is to use closure.

    For example:

    var f = (function () {
      var f = new Function('return this().smth').bind(function () { return f });
      return f;
    })();
    
    f.smth = 128;
    f();
    

    Or so:

    var f = (function (g) {
      return function f() {
        return g.apply(f, arguments)
      };
    })(new Function('return this.smth'));
    
    f.smth = 128;
    f();
    

    Anyway, seems like arguments.callee works inside constructed function regardless strict mode.

    Additional links about the topic: