1

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
Qwertiy
  • 19,681
  • 15
  • 61
  • 128
  • 2
    You cannot. Why would you need to do this (What are you using the `Function` constructor for)? Please provide your actual code so that we can suggest a solution appropriate for your problem. – Bergi Apr 26 '16 at 16:46
  • Maybe have a look at [this approach](http://stackoverflow.com/a/24032179/1048572) for passing values into the constructed function's scope. – Bergi Apr 26 '16 at 16:51
  • 1
    @Bergi, actually I want to [extend function](//stackoverflow.com/q/36871299/4928642), but idea about getting self-reference by the generated function by itself seems interesting for me. – Qwertiy Apr 26 '16 at 17:04
  • Should you delete this question, or should we answer that it's impossible? – Bergi Apr 26 '16 at 21:06
  • @Bergi, answered it. But the answer is useless for question about class. – Qwertiy Apr 26 '16 at 21:17

1 Answers1

0

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:

Qwertiy
  • 19,681
  • 15
  • 61
  • 128
  • 2
    That doesn't return the `new Function()`, but a "bound function" (which e.g. doesn't have a `.prototype`). You could have gotten that easier :-) – Bergi Apr 26 '16 at 21:41
  • @Bergi, _"You could have gotten that easier :-)"_ - how? – Qwertiy Apr 26 '16 at 21:44
  • 2
    By scrapping `new Function` and just returning a closure (created from a function expression), I mean. – Bergi Apr 26 '16 at 21:45