JavaScript pre-parsing and related skills analysis_javascript skills
This article describes JavaScript pre-parsing and related techniques with examples. Share it with everyone for your reference, the details are as follows:
Variable
Similarly, start with the error comparison tips of these two small examples.
alert(y1); //代码段1 var y1 = 'dddd'; alert(y2); //代码段2 // alert(typeof y2); y2 = 'xxxxx';
Think about it first, why one prompts undefined and the other throws an error of undefined variable. . Let’s first look at the JavaScript parsing process.
Javascript will do an event "pre-parsing" before executing the process. The parsing engine will perform the creation of all var variables at the block level and give them an initial value: undefined. In this way, it is obvious why undefined pops up in the first example.
So the first piece of code is actually equivalent to
var y1; alert(typeof y1); //很自然,它此时值为undefined y1 = 'dddd';
Then why does the second piece of code throw an error again? It is no longer in the "pre-parsing" stage. (Here I assume that the browser only does two things when it encounters a script tag: pre-parsing and execution. , in fact, it is not only these two things), but in the execution stage, the reason why the error is thrown is that js does not know the status of y2 in the execution section state (the pre-parsing stage does not capture any information about y2), of course, an undefined error is thrown information. This involves another problem: js is a weakly typed language, and variables can be used without being defined, so why is a definition error thrown here?
Everything happens for a reason. JavaScript always has many strange characteristics of its own, such as the uneven reading and writing of variables. Undefined variables are only writable, not readable. What is writable? Everyone is familiar with this way of writing:
y2 = 'exam'; //在没出现它的定义操作之前(即在它还没有自己的scope之前)该操作会将这段代码认为是定义一个全局变量,在window上注册一个属性y2,并赋值为exam
But when reading it, the js engine cannot find any relevant information about it, so it acts according to its own temper and throws an undefined error without mercy. This is the game rule of js. And but, why can we get its type? Remember how js operates on objects. If you access a non-existent property and type of the object, you will be prompted with undefined (because it is currently a property of the window object).
Another note: A distinction needs to be made here. The reading and writing of variables are not equal. It is only used for variables. It reads the properties of all objects. This feature does not exist. If it does not exist, it will prompt undefined.
Conclusion
Here, the result of my thinking: There are certain similarities between the writing operations of variables and objects. However, each has its own set of rules for reading operations. Because of this, the above problem arises.
In this way, it should be easy to get the answer to the following question.
if (!('a' in window)) { var a = 1; } alert(a);
Function
By extension, function. Remember the pre-parsing mentioned above. In the pre-parsing of javascript, in addition to the pre-definition of the var variable, it also includes the extraction of the definition of the function, so the function can be defined anywhere in the script. , called anywhere. Not limited to what it was before.
But the way to define functions includes a method called literal definition, which uses the var method to declare functions. See below
alert(typeof y3); //结果? var y3 = function (){ console.log('1'); }
Remember this convention: the call must appear after the statement. Why? If you understand the above, the answer here is already clear. The javascript engine will give them an initial value of undefined when pre-parsing var. In this way, if we call it before its declaration, the javascript engine has not yet gotten its true value, and will naturally report "xxx is not a function" Wrong. This also clarifies why they are both function declarations, but one is related to the order of declaration and calling, while the other has no such constraints.
Conclusion
It is a function, the result of js execution and dynamic modification, and still follows the pre-parsing rules of variables (when alerting above, it did not get the information of the literal function).
What if the two are mixed. See below, there are both variables and functions for y4.
alert(typeof y4); //结果? function y4(){ console.log('y4') } var y4;
Because the declaration priority of function in JavaScript pre-parsing is high, y4 is naturally of function type, but after y4 is assigned a value (the js engine is in the execution process at this time), its assignment operation to js will be Override the function's declaration. So:
alert(typeof y5); var y5 = 'angle'; function y5(){ console.log('ghost'); } alert(y5);
The first alert result is function because it is at the top of the js execution process. The second time it alerts, its value has been rewritten to 5 (don’t be fooled by the function’s definition position below.)
Thinking about the parsing and execution of js separately, I found that my eyes suddenly became enlightened, and the answers to many questions naturally emerged. As the author of that article said, "Once you understand the execution environment, calling object, closure Concepts such as packages, lexical scope, and scope chains can easily solve many phenomena in the JS language. "
Looking now, even in this language where there are many incredible things, there are many reasons that can be traced back to it.
How to make better parameter judgment
Having discussed so much above, how can we make it closer to actual development? Since JavaScript has uneven reading and writing, how can we avoid making parameter judgments without reporting errors?
eg:
if(cusVar){ //这里的判断,是不是存在隐含的问题呢。 }
如何严谨一些呢。
if(window['cusVar']) { //保证它不报错。 //或者这样的判断也是可行的 window.cusVar | typeof cusVar !== 'undefined' //干活咯 }
最后补充又一个小quiz, (理解 预解析与执行的分离)
var y7 = 'test'; function fun1(){ alert(y7); var y7 = 'sex'; } fun1();
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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.

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor