I have string containg anonymus function definition, but how i can call this. Lets say function is like so:
var fn_str = "function(){ alert('called'); }";
Tried eval, but got an error that function must have a name.
eval(fn_str).apply(this); // SyntaxError: function statement requires a name
You can use Immediately Invoked Function Expression:
var fn_str = "function(){ alert('called'); }";
eval('(' + fn_str +')();');
Immediately Invoked Function Expression
Another way is to use to a Function object (If you have the function body string):
var func = new Function("alert('called')");
func.apply(this);
You can create functions from strings using the Function constructor:
var fn = new Function("arg1", "alert('called ' + arg1);");
fn.apply(this)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function
Found the solution: Put function in parentheses
var a = "(function(){ alert('called'); })";
eval(a).apply(this);
Related
I have a text string that is correctly formatted as a function and I would like to convert it to an actual function. The text string looks like:
function object_123(){
object_123_Action();
my_clicked(obj);
}
Apart from the word "function" and {}; all other text is dynamically constructed. i.e. It may never contain object_123_Action(), however, it will be something similar, basic function calls. The only issue will be the obj will need to be the object that the function is assigned to.
Basically, I need:
this.func = eval(func_txt); //to actually work.
Where func_txt is:
function object_123(){
object_123_Action();
my_clicked(this);
}
Your string contains a function declaration.
When evaluated, it creates a object_123 variable in the scope of eval (which you can then call later) and returns nothing.
If you want to assign the function to this.func then you need to convert the declaration into a function expression. You can do that by wrapping it in parens.
this.func = eval("(" + func_txt ")" );
var func_txt = "function object_123(){\
object_123_Action();\
my_clicked(obj);\
}";
this.func = eval("(" + func_txt + ")");
var obj = "...";
function object_123_Action() {
alert(1);
}
function my_clicked() {
alert(2);
}
this.func();
You can store your functions in an array on the object.
Then, loop though the functions in another function and execute them.
var myObj = { 'myfunctions': [ ] };
and to add functions:
myObj.myFunctions.push (function () { /*function code here*/ });
Or if you already have a named function:
myObj.myFunctions.push (nameOfFunction);
And to call all the functions, use this function (don't add this function to myObj)
function executeMyFunctions (myObj) {
for (var i = 0; i < myObj.myFunctions.length; i++) {
myObj.myFunctions[i]();
}
}
And if it's possible to avoid using eval, you should.
Try this:
function parseStringToFunction(func) {
func = func || '(function(){return null;})';
return (new Function('return ' + func)());
};
var stringifyFunction = '(function(a, b) { return a+b; })';
var callStringifyFunction = parseStringToFunction(stringifyFunction)(1, 2);
alert(callStringifyFunction); // results is 3
Also read this out: detail about eval() and new Function()
Try this-
$("<script type='text/javascript'></script>").html(func_txt).insertAfter($("script"));
This works:
assert( eval("(function(a, b) { return a+b; })")(1, 2) == 3 )
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#eval_as_a_string_defining_function_requires_(and)_as_prefix_and_suffix
Simply wrap the function in parens.
I want to pass a string to a function that then will use this string as a callback.
e.g.
app.on('notice', function(data) {
var callback = data.func; // this is a string
eval(callback + "()"); // trun string into an executable function
});
However I'm using this in an environment which prevents eval() from being used... How can I rewrite this to work without eval?
I've tried:
var self = this;
return function(){ self[callback]() };
But it doesn't call the function (and I don't get any errors)
Update: I forgot I also need to handle parameters:
e.g.
var params = ['param1', 'param2'];
eval(callback + "("+ params +")");
Use window object.
Replace your eval() call with :
window[callback]();
You could use a Function constructor .
var func = new Function("console.log('i am a new function')");
func();
i am generating dynamic javascript in which i create few functions for storing value
function get[dynamicname](){
return "some value";
}
i want to call this method in another function to get the values of all functions i created
i have all the dynamicnames which i used to create the functions in the function which i am calling..
function getallfunctionvals(){
for ( var i = 0; i < array.length; i++ ) {
var s="get";
var ss="()";
console.log(s+array[i]+ss);
}
}
this is how i am calling the dynamically generated functions but in the console i am getting the function name as string not the value inside it
Hi look at This post.
One of the answer:
if you know that its a global function you can use:
var functPtr = window[func_name];
//functPtr()
Otherwise replace window with the parent object containing the function.
if defined function is in gloabal scope, you can use
window[s+array[i]]()
So if you have a function like getName. what it will do it will call something like
window["getName"]();
you can use eval function. Eg.
var s = eval("function get(){}; gat();");
first of all:
function get[dynamicname](){
return "some value";
}
will generate error: SyntaxError: Unexpected token [
Since "[" is not allowed in javascript function name and variable.
But you can do this:
function getName () {console.log('Name')};
function getAge () {console.log('Age')};
When you invoke the above functions, you can do this:
var s="get";
var thingToGet = "Name";
var ss="()";
eval(s + thingToGet + ss)
Did I answer your question?
Let's say I'm given a string, and I want to define a function with a name of that string. How can I do this?
UPDATE:
I forgot to mention that I do not want to set an anonymous function to a property because I would also like to dynamically grab the function's name from inside the function ie. arguments.callee.name
Like this:
var functionName = "myfunction"
window[functionName] = function() {
// your function here
}
Depending on the requirements, maybe something like this would work:
var myFunctionGenerator = function(name) {return function(message) {
alert("hi, this is a function named '" + name + "'. The parameter passed is '" + message + "'.");
}}
var myFunction = myFunctionGenerator('some function name');
myFunction('a parameter');
// hi, this is a function named 'some function name'. The parameter passed is 'a parameter'.
If your declaring the function, use eval(). Just type a string representation of the argument your trying to execute for example:
eval("function name(){alert('a');}");
You can then call that method by normal convention, name();.
If you already have the function name and want to call that function with a string representation you can use the eval() method, although its not always optimal for performance. You will have this:
var fnName = "functionName";
var params = "param1";
var fnNameWithParams = "functionName("+params+")";
eval(fnNameWithParams);
A better approach may be:
var fnName = "functionName";
var params = "param1";
var fnToCall = window[fnName];
fnToCall(params);
I have a function and its contents as a string.
var funcStr = "function() { alert('hello'); }";
Now, I do an eval() to actually get that function in a variable.
var func = eval(funcStr);
If I remember correctly, in Chrome and Opera, simply calling
func();
invoked that function and the alert was displayed.
But, in other browsers it wasn't the case. nothing happened.
I don't want an arguement about which is the correct method, but how can I do this? I want to be able to call variable(); to execute the function stored in that variable.
How about this?
var func = new Function('alert("hello");');
To add arguments to the function:
var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world
Do note that functions are objects and can be assigned to any variable as they are:
var func = function () { alert('hello'); };
var otherFunc = func;
func = 'funky!';
function executeSomething(something) {
something();
}
executeSomething(otherFunc); // Alerts 'hello'
IE cannot eval functions (Presumably for security reasons).
The best workaround is to put the function in an array, like this:
var func = eval('[' + funcStr + ']')[0];
I realize this is old, but it was the only valid result coming up in my google searches for evaluating anonymous javascript function strings.
I finally figured out how to do it from a post on the jquery google group.
eval("false||"+data)
where data is your function string like "function() { return 123; }"
So far, I have only tried this in IE8 and FF8 (the browsers on my personal computer), but I believe jquery uses this internally so it should work just about everywhere.
Try
var funcStr = "var func = function() { alert('hello'); }";
eval(funcStr);
func();
Use the eval like this :
var func = eval('(' + funcStr + ')');
We solved this problem by preparing universal function parser that convert string to real JavaScript function:
if (typeof String.prototype.parseFunction != 'function') {
String.prototype.parseFunction = function () {
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(this.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
examples of usage:
var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));
func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();
here is jsfiddle
This is also ok.
var func = eval("_="+funcStr);
EVAL without eval()...
function evalEx(code){
var result,D=document,S=D.createElement('script'),
H=D.head||D.getElementsByTagName['head'][0],
param=Array.prototype.slice.call(arguments);
code='function evalWE(){'+code+'}';
S.innerText===''?S.innerText=code:S.textContent=code;
H.appendChild(S);
result=evalWE.apply(this,param);
H.removeChild(S);
return result
}
Usage Example:
ABC=evalEx('return "ABC"');
nine=evalEx('return arguments[1]+arguments[2]',4,5);
A simple example of defining a function as a string, eval()ing it, and passing in a parameter while immediately invoking the function (and then dumping the result to the console):
console.log('eval: %s', eval("(function(foo) { return foo.bar; })")({"bar": "12345"}));
This produces output like the following.
eval: 12345
What also works is
var myFunc = function(myParam){
// function body here
}
function-serialization-tools provides a function, s2f(), that takes a string representation of a function and returns it as a function.