Recently I had asked a question
I needed to programmatically access the onclick attrib of a button which had a function call along with param's in it then supply an extra param & make a function call(onclick=doSomething(2,4)
).
But as I figure out that the use of apply/call
can also come handy to supply extra param's.For this I extracted the the function name from the attribute & it comes in a string like
arr[1] = 'doSomething';
I tried using Function Constructor to treat this as a function but it doesn't work
(like Function(arr[1])
) Why?
Solution mentioned Javascript: interpret string as object reference? works fine. But why it cant be achieved via the function constructor?
Some code info
var funDef ='doSomething'; // this is the name of real function defined in the script
var funcName = new Function(funDef); //expected it to return reference of function doSomething,shows function anonymous() in console
var funcArgs = [5,7,10];
funcName.apply('',funcArgs); //this is the function call.
In this case function does not get called untill I replace
var funcName = new Function(funDef); with var funcName = eval(funDef);
Thanks.