search
HomeWeb Front-endJS TutorialFurther discussion on using functions in JavaScript's eval()_javascript tips

var func = eval("(function(){})");
alert(typeof func);
————————————
A further problem is that the book treats anonymous and The behavior of named functions in JScript and SpiderMonkey is not explained
clearly enough. Okay, this article discusses this issue in depth. It not only involves the content in the book, but also tells a more in-depth
explanation and execution process of JS - in fact, all the content is covered in the book, but it is too Scattered, it is inconvenient to analyze a specific problem specifically
.

First of all, expressions and statements should be made clear. For JS, eval() always tries to execute a statement, so it must
understand the execution text as a statement first. As follows:
---------
eval("1")
---------
From the perspective of JS, since eval() must execute the statement, so "1" is no longer a direct expression, but a direct expression sentence, which is equivalent to "1;". These contents are explained in detail in "5.2.2 Statements, expressions and values ​​during dynamic execution"
.

So, the return value of eval() is actually the return value of the last (valid) clause of the statement. Next, we need to
understand "declaration statements" and "expressions". For example:
───────
function x() {
//....
}
───────
Obviously , which is the "declaration statement" of a named function.Note that the "declaration statement" does not return a value. In other words, the declaration statement is processed by the precompiler during the syntax interpretation period, but it is meaningless during the execution period - it has no
value and no return value. For example, simply "var , it will return the
value (the latter value).

The above rules are the same for JScript and SpiderMonkey, there is no difference. The difference is the following
content. First of all, SpiderMonkey recognizes "function expression". In order to directly implement such a
feature, it assumes that the "function name" appearing in the "function expression" is invalid. Because the "function name" is stated in a "declaration
sentence", and the "expression" is a level smaller (or lower level) than the statement, it cannot be in the "expression
expression" "Statement declaration" appears, so I have to ignore the function name in the expression. In this way, the
following statement in SpiderMonkey:
--------
x = "1234" (function X() {});
------
The function To put it further:
--------
var X = 100;
x = "1234" (function
In these two lines of code, the variable X will not be rewritten because the function name X in the second line is invalid. Regarding these contents
, there is a detailed explanation in the book "5.4.2.1 Problems with Inconsistency between Grammatical Statements and Statement Meanings".

It is in the above section that MS JScript's handling of this problem is also discussed. JScript recognizes function identifier declarations appearing anywhere within the code body
. In other words, since the above identifier is valid, the "X" in the global variable
will be rewritten. However, it is for this reason that JScript must explain the following problem:
----
eval("(function(){})");
eval("( function Since SpiderMonkey recognizes function expressions, it interprets both
as operands of the expression; and JScript needs to recognize the variable name X in the second line of code, so it has to interpret both
as statements. In other words, by default, JScript considers the first line to be an anonymous function "declaration statement" and the second line
to be a named function declaration statement. Therefore, as mentioned before, the "declaration statement" does not return a value, so both
lines of code in JScript return undefined, and the second line of code declares a variable name X.

Regarding this issue, I said in the footnote that the "statement meaning of function declaration" is indeed a bit vague. In any case, just
should be simply understood as JScript thinks this is a "function statement declaration", and SpiderMonkey thinks this is a "function expression
declaration".

Okay. So far, we have probably only explained it clearly:
----
eval("(function(){})");
eval("(function X(){}) ");
------
The effect of these two lines of statements and the reasons for this effect. However, I still have questions about the examples and footnotes in my book. This comes from this text and code:
————————
However, there is an exception in JScript: function literals (here anonymous functions) cannot be obtained in this way. For example, the following code:
var func = eval("(function() { })");
// Output "undefined"
alert(typeof func);
In this case, It can be obtained using named functions (*). For example: ………………
------
First note that this text is context-sensitive. I just want to show how you can assign a valid value to the variable "func". This involves
two methods:
-----
//Method 1, use anonymous function
var func = eval("(function() { })");
alert(typeof func);

// Method 2, use named function
var func;
eval("function func() { }");
alert(typeof func);
------
The meaning of this passage is "It is not possible to use method 1 (using anonymous functions) in JScript, you need to use the second method",
And In the footnote, it is said that SpiderMonkey is just the opposite, and it only refers to this example - in SpiderMonkey, the second method is invalid, but the first method is valid.

What is slightly different from the previous content is that method 2 does not use the "return value", but only uses the effect of the function name declaration in the eval() statement to affect the global variable func . And it is precisely because SpiderMonkey does not recognize the
identifier of this declaration, so it is invalid.

For the same reason, reader I22141 said to change it to the following:
---- ----
In SpiderMonkey, the return value is used, which is no longer the same problem as the above example. So what I22141
asked "(So what do you mean when you say that eval() can be used to return an anonymous function in SpiderMonkey, but named functions can only
return undefined?)" is also divorced from this An example question.

Finally, let’s talk about a detail issue. This is not mentioned in the book. In fact, it is also a very weird incident. First of all, in
I said above that in JScript:
--------
// The first case
var func = eval("(function(){}) ");
alert(typeof func); // Display "undefined"
--------
Undefined is displayed here because JScript interprets the following function as an anonymous function declaration, so there is no value. In fact, it is a bit more far-fetched than
. Because let’s modify it:
————————————
// The second case
var func = eval("(1, function(){})");
alert (typeof func); // Display "function"
------
is different. So why in the first case, JScript must be understood as a "declaration statement" rather than an expression? I don't know for sure. I just start from:
--------
// The third case
var X;
eval("(function X(){})");
alert(typeof What's even more strange is that I don't know why JScript allows a "statement" within an expression operator "(...)" - because theoretically, this situation
It is difficult to interpret in grammatical analysis. I even mentioned the following code in "5.4.2.1 The problem of inconsistency between syntax declaration and statement meaning":
---------
// Example 5: Rewriting in the syntax declaration stage
// Rewrite
(function Object(){
}).prototype.value = 100;

// Display value undefined
var obj = new Object();
alert(obj.value);
--------
is because the function X in "(X).prototype.value" during the execution period and the statement analysis period cover the global The functions of the Object identifier
are not the same. But, I still don't understand why JScript allows declaration statements in expressions.
What is even more contrary to this is that if such an assumption is to be admitted, then why the following statement cannot be executed:
---------
(var x=100);
-------- 🎜>--------
OH... I am still confused as to the final answer to this question.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment