Reputation: 27375
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
.
Upvotes: 2
Views: 83
Reputation: 19679
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
Upvotes: 1
Reputation: 27823
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\';'))());
Upvotes: 1
Reputation: 7416
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.
Upvotes: 1