2

If we write

mase_me= new Function('','return \'aaa\';');
alert(mase_me.toString());

then displays function anonymous() { return 'aaa'; }. Further i'm trying to call function, I'm write

alert(anonymous());

but i have an error

[18:23:40.220] ReferenceError: anonymous is not defined @ http://fiddle.jshell.net/_display/:33

I'm excepted that alert(anonymous()); will display aaa because if I write

made_me=function aaa() { return 'aaa'; }
alert(made_me.toString());

then will display function aaa(){ return 'aaa'} and

alert(aaa());

will display aaa.

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 3
    anonymous means "unnamed" ... Javascript tells you that the function doesn't have a name. So you cannot just use `anonymous` as if it was the name of the function – devnull69 Dec 18 '13 at 17:26

3 Answers3

1

Any time you do a new Function(), it is called an anonymous function. They are for the purpose of closures. However, you should always us a literal, such as [], "", and function(){}, instead of new Function().

To call the function, you should do mase_me(), not anonymous(), since anonymous is the name given to any function constructed like that.

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
1

anonymous is not the function's name. It is simply an indicator that the function has no name, a placehoder if you wish.

While you can't call an anonymous function by name, you can call it by using a reference to it. You have such a reference in the mase_me variable:

alert(mase_me()) // alerts 'aaa'

The only other way to call it is by calling it immediately when it is constructed, but i doubt it would help in your case:

alert((new Function('','return \'aaa\';'))());
Tibos
  • 27,507
  • 4
  • 50
  • 64
1

anonymous is the name of the function, not the name of the variable containing a reference to the function — that is mase_me.

You can see that because new Function('','return \'aaa\';').name === "anonymous".


When you do:

function aaa() { return 'aaa'; }

It is effectively the same as:

var aaa = function aaa() { return 'aaa'; }

(note that is is not exactly the same: var functionName = function() {} vs function functionName() {})


Naturally, this works the same with functions created in such a way that have been given an explicit name:

var a = new Function("b", "return 'aaa';");
a(); // works
b(); // doens't work (not defined)
a.name === "b" // true
Community
  • 1
  • 1
Tom Leese
  • 19,309
  • 12
  • 45
  • 70
  • That's interesting, must be a Moz-only thing. In Chrome, `new Function().name` and `(function(){}).name` are both an empty string. In Moz, `new Function().name` is "anonymous" but `(function(){}).name` is an empty string. Weird. – Dagg Nabbit Dec 18 '13 at 17:50
  • I was actually surprised myself that the name of `new Function()` was equal to `"anonymous"` in Firefox, I was expecting it to be an empty string like `(function(){}).name`! The behaviour in Chrome seems more sensible to me. – Tom Leese Dec 18 '13 at 17:51