I recently asked a question
Extract and call the JavaScript function defined in the HTML attribute of the onclick element (using jQuery attr / prop)
I needed to programmatically access the onclick attribute of a button in which there was a function call along with a parameter, and then provide an additional parameter and call the function call ( onclick=doSomething(2,4) ).
But as I find out that using apply/call can also come in handy to provide additional options. To do this, I extracted the function name from the attribute and came to a string like
arr[1] = 'doSomething';
I tried using the Function Constructor to treat this as a function, but it does not work (for example, Function(arr[1]) ) Why?
Solution mentioned by Javascript: interpret string as object reference? works great. But why is this impossible to achieve through the function constructor?
Some code information
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, the function is not called until I replaced
var funcName = new Function(funDef); with var funcName = eval(funDef);
Thank.
javascript jquery javascript-objects
techie_28 May 23 '16 at 10:05 2016-05-23 10:05
source share