search
HomeWeb Front-endJS TutorialSummary of usage examples of eval and with in javascript_javascript skills

The examples in this article describe the usage of eval and with in javascript. Share it with everyone for your reference, the details are as follows:

We all know the scope mechanism of JavaScript, but with and eval sometimes "destroy" our conventional understanding of scope. Let’s summarize the usage of eval and with with reference to online resources and your own understanding.

1. eval

1. eval function: treat a string as a js expression to execute it.

2. Syntax: eval(strScript) Note: The parameter strScript is required

3. Instructions for use

(1) It has a return value. If the parameter string is an expression, the value of the expression will be returned. If the parameter string is not an expression and has no value, then "undefined" is returned.
(2) When the parameter string is executed as code, it is related to the context in which the eval function is called, that is, the variables or function calls that appear in it must be available in the context in which eval is called.

4. Example:

function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } //eval,这个比较常用
var myTest = function() { return "eval test"; };
function evalTest() {
  //简单数据
  alert(eval("1+1")); //2
  alert(eval("'a'+1")); //a1
  alert(eval("1+'a'")); //1a
  alert(eval("parseInt('a'+1)")); //NaN
  alert(eval("parseInt(1+'a')")); //1
  alert(eval("true")); //true
  alert(eval("0==false")); //true
  alert(eval("1==undefined")); //false
  alert(eval("isNaN(undefined)")); //true
  //函数和对象
  alert(eval("this")); //[object]
  alert(eval("typeof(this)")); //object
  alert(eval("typeof(test)")); //undefined
  alert(eval("evalTest")); //这个显示当前函数的定义语句细节,包含注释
  //alert(eval("evalTest()")); //调用自己并执行,这个会有大问题啊!
  alert(eval("typeof(evalTest)")); //function
  //其他
  var tmpFunc = "{a:1}";
  alert(eval(tmpFunc)); //1
  alert(eval("(" + tmpFunc + ")")); //[object object]
  alert(eval("tmpFunc")); //{a:1}
  //alert(eval("tmpFunc()")); //脚本错误
  alert(myTest());
  eval("alert(myTest())"); //和上面等价
  alert(eval(myTest));
  alert(eval("myTest")); //和上面等价
  //form里的一个input,id=txtUserName
  eval("$('txtUserName').value='jeff wong';"); //等价于 $('txtUserName').value = 'jeff wong';
  eval("alert( $('txtUserName').value);");
}
evalTest(); 

5, eval and scope

(1) Classic code analysis

a. Common

var str = "global";
function test() {
  alert(str); //undefined
  var str = "local";
}
test();
alert(str); //global

Analysis: As we expected, the specified value is obtained. The results of str in the test function without var and with var declaration are also different. Readers can verify by themselves.

b, eval instead of directly declaring variables

var str = "global";
function test() {
  alert(str); //??
  eval("var str='local';");//会像我们预期的那样吗?
  //var str = "local";
  alert(str); //这里又是什么结果?
}
test();
alert(str); //??

Analysis: Compared with the writing method in a, we just use the eval statement in the test function to replace the sentence that directly declares var to define the variable and just alert at the end. The results are very different.

(2) eval defines global code

a. The eval function that is compatible with IE and FF and defines global code

var nav = new Object();
//通用eval函数
nav.Eval = function(jsCode) {
  if (document.all) //IE下是execScript
   execScript(jsCode);
  else window.eval(jsCode); //FF下是window.eval
}

For IE browser, the function execScript is used to execute code in the global space.
For the Firefox browser, if the eval function is called directly, it will be executed in the caller's space; if window.eval is called, it will be executed in the global space; but the return value of alert(eval==window.eval) is true, which is strange ff.

b. Call the test code of a

var nav = new Object();
//通用eval函数
nav.Eval = function(jsCode) {
  if (document.all) //IE下是execScript
   execScript(jsCode);
  else window.eval(jsCode); //FF下是window.eval
}
function test() {
  nav.Eval("var str = 'global';"); //这里声明变量str,在外面的函数中可以调用变量
  nav.Eval("var tmpFunc = function(){alert('global function');};"); //这里声明函数变量tmpFunc,在外面的函数中可以调用函数
  alert(str); //global
  tmpFunc(); //global function
}
test();
alert(str); //global (调用nav.Eval函数声明的全局变量)
tmpFunc(); // global function (调用nav.Eval函数声明的全局函数)

Analysis: Through the code in b, you may have discovered an obvious inconvenience of eval defining global code, that is, for global code, js smart prompts (here vs, and other tools may also) are completely lost. Prompt function. From this, you will definitely ask, if a lot of global code is defined in the program through eval, will its maintainability be too low? My opinion is that I agree with the summary on the Internet and use eval less. After all, ready-made tools cannot provide good prompts, and programmers' eyesight is often not that good.

2. with

1. with statement: Specify a default object for one or a group of statements, usually used to shorten the amount of code that must be written in a specific situation .
2. Grammar: with ()
with (object)
statements
(1) Parameter object: new default object;
(2) statements: one or more statements, object is the default object of the statement.

3. Example:

function withTest() {
 with (document) { //document的重复使用
 writeln("Hello,");
 writeln("it's a with keyword test!");
 }
 with (Math) { //Math的重复使用
 alert(random());
 alert(abs(-10));
 }
}
withTest();

4. with will temporarily modify the scope chain

function withTest() {
 var userName = "jeff wong";
 //暂时修改作用域链
 with (document) {
 writeln("Hello,");
 writeln(userName);
 }//with内的语句执行完之后,作用域链恢复原状
 alert(userName);
}
withTest();

Analysis: When the function withTest is defined, the scope chain of withTest is determined. We temporarily think that the top of this scope chain is the window object. When withTest is executed, the js engine generates a call object (calling object) and add it to the end of the scope chain (after the window object). When the statement runs to with(document), a new scope will be generated (in essence, this scope is the same as the scope of an ordinary function, except that However, after the with clause is executed, the scope disappears) and is added to the end of the scope chain, so when searching for variables within with, priority will be given to the with (document) scope of this chain. , then search from the call object of withTest, and finally search for window. After the statement within with is executed, the scope chain is restored to its original state (the scope generated by with(document) is moved out of the scope chain).

ps: with is not recommended because it requires operating the scope chain (moving in and out of the scope), which results in low execution efficiency.

I hope this article will be helpful to everyone in JavaScript programming.

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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor