-2

I wonder how the JS on this site is executed when you click on "run":

http://ejohn.org/apps/learn/#3

It's not like JSFiddle, so he didn't use IFrames.

I searched the web and found reptl.it, that executes code too. I don't know if it works the same way. Can please someone explain the magic?

gform
  • 5
  • 1

2 Answers2

2

Looking at the source code, they just create a function containing the code in the textarea, using the Function constructor which takes the function body as a method. Then they call the function:

try {
    (new Function( jQuery("#code").val() ))();
} catch(e){
    error(e.message);
}

This works in a very similar way to eval with the exception that the new function cannot access variables in the current scope, as the Note in the link states:

Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
2

When you click run, it's submitting a <form> that contains the code. The form submit however is handled in javascript, with the below code handling the running of the entered script:

try {
    (new Function( jQuery("#code").val() ))();
} catch(e){
    error(e.message);
}

In essence, it's creating a new function using the Function constructor and immediately running it. The assert, log and error functions are normal functions defined elsewhere on the page. Any errors are caught with the catch and passed off to the same error function.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93