Current location - Education and Training Encyclopedia - Education and training - Did Yunnan java Training School tell you about possible bugs in JavaScript?
Did Yunnan java Training School tell you about possible bugs in JavaScript?
For every programmer, it is very normal for bugs and errors to appear in the programming process, as long as we eliminate the problems before going online. Today, let's look at the problems in JavaScript.

Working mechanism of call stack

Before discussing the errors in JS, we must understand the working mechanism of CallStack. In fact, this mechanism is very simple. If you know this, you can skip this part directly.

Simply put, when a function is called, it will be added to the top of the call stack, and after execution, it will be removed from the top of the call stack. The key to this data structure is LIFO, which is also known as LIFO. For example, when we call function X inside function Y, the order of calling stack from bottom to top is Y->; Ten.

Error Object and Error Handling

When an error occurs in the code, we usually throw an error object. Error objects can be used as prototypes to extend and create custom error types. The prototype of the error object has the following properties:

Constructor_ is responsible for the prototype constructor of this instance;

Message_ error message;

Name_ Wrong name;

The above are all standard attributes, and some JS runtime environments also provide attributes other than standard attributes, such as Node.js, Firefox, Chrome, Edge, IE 10, Opera, Safari6+, which all contain the call stack of error codes, and we will call it the error stack for short. The error stack contains the complete call stack information at the time of the error. If you want to know more about the nonstandard properties of the Error object, I strongly recommend that you read this article of MDN.

You must use the throw keyword when throwing an error. In order to catch the error thrown, you must use a trycatch statement to wrap the code block that may be wrong. When capturing, you can receive a parameter, which is an error thrown. Similar to Java, JS can also have finally after the trycatch statement, and the code in finally will be executed regardless of whether the previous code throws an error or not. The common usage of this language is to do some cleaning work at the end.

Clipping of error stack

Only Node.js supports this feature, which is realized by error.capturestacktrace, which receives an object as 1 parameters and an optional function as 2 parameters. IT training/ thinks its role is to capture the current call stack and cut it. The captured call stack will be recorded on the stack attribute with 1 parameters, and the reference point of cutting is 2 parameters, that is, the previous call of this function will be recorded on the call stack, and the subsequent call will not.