Home Web Front-end JS Tutorial Further discussion on using functions in JavaScript's eval()_javascript tips

Further discussion on using functions in JavaScript's eval()_javascript tips

May 16, 2016 pm 07:02 PM
javascript function discuss

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

Advanced usage of reference parameters and pointer parameters in C++ functions Advanced usage of reference parameters and pointer parameters in C++ functions Apr 21, 2024 am 09:39 AM

Reference parameters in C++ functions (essentially variable aliases, modifying the reference modifies the original variable) and pointer parameters (storing the memory address of the original variable, modifying the variable by dereferencing the pointer) have different usages when passing and modifying variables. Reference parameters are often used to modify original variables (especially large structures) to avoid copy overhead when passed to constructors or assignment operators. Pointer parameters are used to flexibly point to memory locations, implement dynamic data structures, or pass null pointers to represent optional parameters.

See all articles