JavaScript (4) -- advanced skills

01 Preface

DOM and BOM are the two most basic modules of JS. Through these two modules, we can manipulate the structure and style of HTML documents, and control the behavior of the browser. However, the advanced features of JS go far beyond that, including functional programming, closures, scopes, prototype chains, and more. These concepts and techniques can not only improve the programming ability of JS, but also allow developers to write more efficient, concise and maintainable code. Therefore, in this article, we will explore the advanced features of JS in depth, so that readers can more fully understand and apply the advanced skills of JS in actual development.

02 Abnormal

2.1 Exception

  Errors or exceptions in JavaScript code are called Exception. Starting from ES3, JavaScript also provides a similar exception handling mechanism to make JavaScript code more robust. Even if an exception occurs during execution, the program can also have a part of the exception recovery capability.

  When JavaScript code executes, if it encounters an error or unusual condition, it throws an exception. This exception will interrupt the normal execution flow of the code, and output the corresponding error message on the console to prompt the developer to make corrections in the code.

  Common exception types in JavaScript include syntax errors, type errors, reference errors, range errors, null object reference errors, and more. Developers can use try-catchstatements to catch exceptions and execute corresponding code when exceptions occur so that these exceptions can be handled during program execution.

The thrown error will return roughly the following types:

wrong name describe
EvalError Errors that have occurred in the eval() function
RangeError A number out of range error has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError Errors that have occurred in encodeURI()

2.2 Throwing exceptions

In JavaScript, use the try-catch statement to catch exceptions, and its basic syntax is as follows:

try {
    
    
    // 可能发生异常的代码
} catch (error) {
    
    
    // 发生错误执行的代码
} finally {
    
    
    // 无论是否出错都会执行的代码
}

In this syntax form, trythe following code block contains code that may throw an exception. If an exception is thrown in this code block, the program will immediately jump to the catchfollowing code block and execute theexception handling code

The parameter error behind catch is a variable representing the exception object. Developers can use this variable in the catch code block to access the details of the exception, such as exception type, exception message, etc.

Note that try-catch statements can be nested to handle exceptions at different levels of the program. Also, you can add blocks inside a try block finally, and the code in the finally block will be executed regardless of whether an exception occurs or not. That is to say, the statement in the finally will be executed after the statement in the try is executed without error, and the statement in the catch will be executed if the statement in the try has an error, and the statement in the finally will also be executed after the statement in the catch is executed.

In JavaScript, if a finally statement is added, the catch statement can be omitted. But if there is no catch statement, once an error occurs, the error cannot be caught, so after the statement in finally is executed, the program will stop immediately. Therefore, in actual use, it is best to always have a catch statement. If you write a catch statement, the finally statement can also be omitted.

2.3 Actively throwing exceptions

In JavaScript, we can use throwstatements to actively throw exceptions. This means that when the program reaches the throw statement, it immediately stops the current execution flow and throws a specified exception.

Here's a simple example that throws an exception:

function divide(x, y) {
    
    
  if (y === 0) {
    
    
    throw new Error('Division by zero');
  }
  return x / y;
}

try {
    
    
  let result = divide(10, 0);
  console.log(result);
} catch (error) {
    
    
  console.error(error.message);
}

In this example, we define a function called divide that performs the division of two numbers. If the value of the second parameter y is 0, an exception is thrown and the exception message is output in the exception handling code block.

In the try block, we call the divide function and assign its result to the variable result. Since the second parameter is 0, the divide function throws an exception, causing the program to immediately jump to the catch block and output an exception message.

By proactively throwing exceptions , we can detect and handle unexpected situations in our code. For example, when reading a file, if the file does not exist, we can use the throw statement to throw an exception, and output error information in the exception handling code block, so as to find and solve these problems in time.

03 June

3.1 Overview

JSONIt is a lightweight data exchange format, called JavaScript Object Notation, which represents data in the form of text, and has good readability and scalability. The data structure of JSON is based onkey value pair, which can be used to store and transmit structured data. In web development, JSON is usually used for data interaction between front and back ends.

3.2 Features of josn

Why use JSON? Because JSON has the following advantages:

  • Simple and easy to use: The grammatical rules of JSON are simple and clear, easy to understand and use.
  • Good readability: The text format of JSON is easy to read and debug, which is convenient for developers to analyze and process data.
  • Cross-platform support: Data in JSON format can be supported by multiple programming languages ​​and platforms, which facilitates cross-platform data transmission and sharing.
  • Small data volume: Compared with other data exchange formats, the data volume of JSON is usually smaller and the transmission speed is faster.

Compared with CSV (Comma-Separated Values), the advantages of JSON are:

  • Clearer structure: CSV is just a comma-separated text file without a clear structural representation, making it difficult to describe complex data structures; while JSON uses key-value pairs to represent data, the structure is clearer, and complex data structures can be stored.
  • Better scalability: JSON supports nesting and arrays, you canStore any level and type of data, while CSV only supports one-dimensional tabular data.
  • More flexible processing: JSON supports the format of JavaScript objects, which can be directly processed through JavaScript's built-in methods, while CSV needs to implement parsing and processing logic by itself.

To sum up, JSON is a more flexible, more readable, and more scalable data exchange format, suitable for various data exchange scenarios.

3.3 josn syntax

There are some differences between JSON objects and JavaScript objects:

  • A JSON object is a special kind of JavaScript object whoseattribute nameMust be a double- quoted string, while JavaScript object property names can be any valid JavaScript identifier.
  • JSON objects do not support function attributes, while JavaScript objects can have function attributes.
  • JSON objects cannot contain circularly referenced properties, while JavaScript objects can contain circularly referenced properties.


JSON.stringify()JSON objects and JavaScript objects can be converted to each other, and the and methods provided by JSON objects can be used JSON.parse()to realize the conversion.

The JSON.stringify() method can convert JavaScript objects into JSON strings, for example:

let person = {
    
    
  name: 'Alice',
  age: 25,
  address: {
    
    
    city: 'Shanghai',
    street: '123 Main St'
  }
};

let jsonStr = JSON.stringify(person);
console.log(jsonStr);
// 输出:{"name":"Alice","age":25,"address":{"city":"Shanghai","street":"123 Main St"}}

The JSON.parse() method can convert JSON strings into JavaScript objects, for example:

let jsonStr = '{
    
    "name":"Alice","age":25,"address":{
    
    "city":"Shanghai","street":"123 Main St"}}';
let person = JSON.parse(jsonStr);
console.log(person);
// 输出:{ name: 'Alice', age: 25, address: { city: 'Shanghai', street: '123 Main St' } }

04 AJAX

4.1 Overview of AJAX

The full name of AJAX is Asynchronous JavaScript And XML, which is an asynchronous data exchange technology based on JavaScript and XML technology. It can request data from the server without reloading the entire page, and update the partial content of the page in real time, thereby improving the response speed and user experience of the page.

The following are some animation and film sites in China that use AJAX technology:

Dilidili Animation Network: https://www.dilidili1.com/
Anime House: https://www.dmzj.com/
Bilibili Animation: https://www.bilibili.com/anime/
These websites provide It collects a large number of animation resources, and uses AJAX technology to realize dynamic loading and interaction, so that users can browse and watch animation more conveniently.

05 closure

5.1 Closure concept

A closure means that a function can access and manipulate variables within the scope of its outer function, even if the outer function has returned, the closure can still retain access to these variables. In simple terms, a closure means that after the function is executed, the variables inside the function can still be accessed.

5.2 Case Description

A typical application of closures is to use a function as the return value of another function, thus forming a "private" scope that prevents external access to internal variables and functions.

Here is an example of a JS closure:

function outerFunction() {
    
    
  var outerVariable = "I am outer";
  
  function innerFunction() {
    
    
    var innerVariable = "I am inner";
    console.log(outerVariable + ", " + innerVariable);
  }
  
  return innerFunction;
}

var innerFunc = outerFunction();
innerFunc(); // 输出 "I am outer, I am inner"

In the above example, outerFunctionan inner function is defined in innerFunctionand the inner function accesses the variables of the outer function outerVariable. outerFunction finally returns innerFunction as the return value, which is stored in the variable innerFunc.

Since innerFunc refers to the variable outerVariable in outerFunction, outerVariable will not be released by the garbage collection mechanism even though outerFunction has been executed. When innerFunc is called, it still has access to the value of outerVariable and outputs "I am outer, I am inner".

This example shows a basic usage of closures, which is to define another function inside a function, so that the inner function can access the variables and parameters of the outer function, so as to achieve some advanced programming skills.

Guess you like

Origin blog.csdn.net/qq_54015136/article/details/130008259