Skip to content Skip to sidebar Skip to footer

Function Typecasting Javascript

Recently I had asked a question Extract & call JavaScript function defined in the onclick HTML attribute of an element(using jQuery attr/prop) I needed to programmatically acce

Solution 1:

new Function and eval are not interchangeable. When you eval, you are creating code that runs immediately. When you create a Function, that is going to return a function that you can run yourself.

It's almost as if you do:

// This executes 1+2var resultOfEval = eval('1+2');
// This creates a function that when called, returns 1+2var resultOfWrappedEval = eval( '(function(){return 1+ 2})' );
// This is much like the line above, you have to call it for it to executevar resultOfFunctionCtor = newFunction('return 1+ 2;');


console.log('resultOfEval', resultOfEval);
console.log('resultOfWrappedEval', resultOfWrappedEval);
console.log('executing resultOfWrappedEval', resultOfWrappedEval());
console.log('resultOfFunctionCtor', resultOfFunctionCtor);
console.log('executing resultOfWrappedEval', resultOfFunctionCtor());

If you show more of your code, we can suggest something, but the key is that when calling the Function constructor, the code doesn't run immediately, it returns a reference to the newly created function.

Also, you seem to understand that you can call the function yourself. What is the problem with doing that?

Solution 2:

I discussed this on the JavaScript chat room from where I understood that new Function(..) constructor needs whole function body to return reference in the way I was expecting.

The function constructor does not consider the definition of the doSomething function that is written in the script while eval does.

Other ways that could be fit in this scenarios are here:

Javascript use variable as object name

Comments?

Post a Comment for "Function Typecasting Javascript"