Note that there are some explanatory texts on larger screens.

plurals
  1. POJS Function-constructor re-parsed everytime?
    text
    copied!<p>In MDN, about <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope#Function_constructor_vs._function_declaration_vs._function_expression" rel="nofollow">Functions and function scope</a>, what does it mean by <strong>parsed every time it is evaluated</strong>? Can this be observed by codes?</p> <p>Quote in the section <strong>Function constructor vs. function declaration vs. function expression</strong>:</p> <blockquote> <p>Functions defined by function expressions and function declarations are <strong>parsed only once</strong>, while those defined by the Function constructor <strong>are not</strong>. That is, the function body string passed to the Function constructor must be <strong>parsed every time it is evaluated</strong>. Although a function expression creates a closure every time, the function body is <strong>not reparsed</strong>, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should be avoided whenever possible.<p> It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string <strong>aren't parsed repeatedly</strong>. For example:<p><code>var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();<br/> foo(); //The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.</code></p> </blockquote> <p>I have written a code snippet to (try to) test and understand it:</p> <pre><code>var bar = 'FOO!'; var foo = (new Function("return(function() {\n\talert(bar);\n});"))(); bar = 'FOO! again'; foo(); //The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed. var bar2 = 'FOO!2'; var foo2 = function() { alert(bar2); }; bar2 = 'FOO!2 again'; foo2(); </code></pre> <p>Both two alerts the "again-version".</p> <p>What does it mean by <strong>reparsed</strong> or not?</p> <p>Can this be illustrated by code results?</p> <p>Thanks.</p> <hr> <p>FYI, i have tried another code snippet:</p> <pre><code>var bar = 'FOO!'; var string1 = "return(function() {\n\talert(bar);\n});"; var foo = (new Function(string1))(); bar = 'FOO! again'; foo(); //The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed. string1 = "return(function() {\n\talert(bar + ' more');\n});"; foo(); </code></pre> <p>Both alerts "FOO! again", <strong><em>not</em></strong> "FOO! again more".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload