TruthSeeker TruthSeeker - 6 months ago 15
Javascript Question

Recommended way to Execute a function stored as String in JavaScript instead of using eval

Before anyone marks it as duplicate, this post does not actually answer the question but suggests a different way altogether to solve that particular issue.

Mine is a different issue. Please let me explain.

In my case, there are various

.js
files (plugins) which are being loaded with
jquery getscript
and stored in variables. Then whenever required they will be executed (more than once)

The code for loading script (this code will only run once at the init of the system for each plugin js file)

var storedFunc;
$.getScript(pathToPluginJSFile, function( data, textStatus, jqxhr ) {
storedFunc = data;
});


All the plugins are in this format

(function(){
//lots of code here
})()


But when I checked the
storedFunc
variable in console, I found out that it has been stored as String variable. Like this,

"(function(){
//lots of code here
})()"


Now to execute this, I used
eval
, like this (this code can be executed multiple times based on the need)

eval(storedFunc)


Everything is working fine and i am happy with it, but here comes the problem, I read in somewhere that the usage of
eval
is kind of like a bad thing to do. So now I am afraid that thought everything is working fine, all these negativity of using eval spread on the internet might scare my client away. :(

So, please tell me how I can run that stored function (which has become a string) without using eval.

Or should I use anything else than
$.getScript
which does not convert a function into a string ?

Or if there is any other way altogether rewriting this plugin functionality?

Please show me the way. I am in need of this solution badly.

Any help will be appreciated.

Thanks in advance.

Answer

Understanding how $.getScript works

Seems there is some confusion on how $.getScript works. If you notice jQuery's documentation on the method, and as @Pointy made mention of in the comments, this is stated:

Load a JavaScript file from the server using a GET HTTP request, then execute it.

Here's an example: Let's pretend the contents of the file being returned is only this:

// Contents of yourExternalFile.js
console.log('Executed!');

Now, when you use $.getScript:

$.getScript(pathToPluginJSFile, function( data, textStatus, jqxhr ) {
    // The script you retrieved has already executed at this point, and you will find "Executed!" in the console.
    console.log('All Done');
});

Console output:

> Executed!
> All Done

The $.getScript method is not meant to be used to return a string of the content of the file. However, while that data is available in the callback, the contents of the file have already been executed. So by taking the string version of the file, and re-executing it with either new Function, or even eval, you are executing it twice on the page (jQuery does it once, and so do you).


Original Post:

Use the Function constructor instead of using eval.

// Your function as a string stored to a variable
var stringFunction = "(function(){console.log('Executed');})()";

// Use the Function constructor to create a new function:
var executableFunction = new Function(stringFunction);

// Now you can execute it
executableFunction(); // logs "Executed"

This snippet from this SO question/answer addresses the difference between eval and new Function.

  • eval() evaluates a string as a JavaScript expression within the current execution scope and can access local variables.

  • new Function() parses the JavaScript code stored in a string into a function object, which can then be called. It cannot access local variables because the code runs in a separate scope.


Additional Information (Based on comments)

Yes, you can just get the string contents of the file and store them to a variable without the contents of the file executing. You can have that function to execute anytime. You just need to use the regular get method using jquery, and set the dataType to text. This way, the script will not execute, and you can execute it as you see fit:

var storedFunction;

$.get({url: pathToPluginJSFile, dataType: 'text'})
    .done(function (data) {
        // Turn the script into a new function and store it
        // The information in the script file has not done anything yet
        storedFunction = new Function(data);
    })
    .fail(function () {
        console.log('Failed :(');
    });

// Call that function anytime, and as often as you want:
storedFunction();
Comments