Hello, I’m Yue Chuang.

Today we’re going to focus on the basics of JavaScript reversibility and the necessary JavaScript syntax and some of the more advanced stuff.

directory

  1. JavaScript introduction

    1.1 JavaScript introduction

    1.2 Web Three Musketeers

    1.3 JavaScript development

  2. JavaScript syntax

    2.1 Data Types

    2.1.1 Object

    2.1.1.1 Object Data Structure

    2.1.2 Array Array

    2.1.3 String The character String is a String

    2.1.4 Number Number

    2.1.5 Boolean Indicates the Boolean value

    2.1.6 Map mapping

    2.1.7 Set collection

    2.1.8 NULL/Undefined (2.1.9)

    2.2 the control flow

    2.2.1 Condition judgment

    2.3 the function

    2.3.1 definition

    2.3.2 Variable scope

    2.3.3 Higher-order functions

    2.3.4 closure

    2.3.5 Special Objects

  3. JavaScript advanced

  4. conclusion

In the first section, I’ll give a brief introduction to the background of JavaScript, its evolution, and how it relates to CSS AND HTML.

The second section is the focus of this lesson. I will focus on the syntax of JavaScript, including variable types, functions and control flow.

The third section is the advanced content of this lesson. I will introduce some advanced knowledge of JavaScript, including event loop, prototype chain, asynchronous programming and so on. These advanced content are the basic knowledge that we may encounter when dealing with JS reverse.

Finally, I will make a summary of the above knowledge points.

1. Introduction of JavaScript

1.1 JavaScript introduction

As we all know, JavaScript is a weakly typed language, flexible and powerful, and indispensable programming language for the front-end domain. There’s also something going on in the back-end, but where does it come from?

Here IS a brief introduction: JavaScript was originally invented by Brendon Eich of Netscape and originally called LiveScrip. According to Baidu Baike, 34-year-old Brendon Eich worked on it in just 10 days. I invented JavaScript. However, the lack of rigorous reasoning and design resulted in a mess of subsequent programs (actually due to the rise of multiple versions, but the advent of JavaScript has solved the original web page refresh time). JavaScript at the time referenced C, Java, Scheme, and Self. JavaScript, therefore, is the product of functional and object-oriented programming, which is equivalent to a similitar.

** * However, ** * has since become one of the most popular languages on the Internet, sweeping the world.

JavaScript has since been competing with Microsoft’s JScript and CEnvi’s ScriptEase. In 1997, the European Computer Manufacturers Association (ECMA) coordinated the unification of several versions of JavaScript into a single standard called ECMA-262 and released ECMAScript 1.0, or ES1. This laid the foundation for the rapid development of JavaScript.

ES2 and ES3 were released in 1998 and 1999, respectively, and ES5 was released 10 years later in 2009. Many of the modern syntax and data structures in ES5 are the foundation of modern JavaScript, and most of today’s JS features are based on this version (ES5).

Six years later, in 2015, ES6 was released, and it was a huge improvement on ES5. Features like Promise that solves callback hell. So, in Darwinian terms, JavaScript has grown from a primitive gorilla into a full-fledged and powerful modern human over the course of 20 years.

In order to let students more intuitive understanding, I summarized it as follows:

  • JavaScript was invented more than 20 years ago by Brendan Eich of NetScape and originally named LiveScript
  • It changed its name to JavaScript in order to keep up with the popular Java, competing with Microsoft’s JScript and CEnvi’s ScriptEase
  • In 1997, under the coordination of ECMA (European Computer Manufacturers Association), a working group composed of NetScape, Sun, Microsoft and Borland determined a unified standard: ECMA-262 and released ECMAScript 1.0, or ES1 for short
  • ES2 was released in 1998 and ES3 in 1999
  • ES5 was released in 2009, and most JS features are in this version today
  • ES6 was released in 2015 with a number of utility feature improvements

1.2 Web Three Musketeers

JavaScript is said to be the front-end language, and we know that the front-end is known as the three musketeers of the web page, which are the three musketeers?

  • JavaScript
  • CSS
  • HTML

So what’s the relationship between them?

  • HTML is the structural layer, equivalent to the human skeleton and body

    For example: headings, paragraphs, lists, etc.

  • CSS is presentation, equivalent to people’s clothes and decorations

    For example: font, background, color, border, size and so on;

  • JavaScript is the behavior layer, equivalent to human actions and actions

    For example: clicking scroll bars, events and back-end interactions, widgets, clicking pop-ups, dynamic displays, and so on.

1.3 JavaScript development

The name of the content
The front end React, Vue, Angular
The back-end Node.js
The desktop Electron
The Internet of things Arduino
The database MongoDB
The mobile terminal React Native

At present, JavaScript is versatile because of its flexible and easy-to-use nature.

  1. I’m not going to talk about the front end, but JavaScript is definitely dominant;

  2. Node.js is a very flexible back-end language;

  3. There’s Electron on the desktop, which is where THE famous VS Code was developed;

  4. The Internet of things has Arduino;

  5. The Shell of MongoDB database also uses JavaScript;

  6. JavaScript is also evolving on the mobile side. We have excellent frameworks like React Native to simplify the development process on the mobile side.

As a result, we can see that JavaScript is very versatile. We have reason to believe that JavaScript will continue to grow and become popular in the future, and learning such a versatile language is very important (and helpful).

With the background and development of JavaScript behind us, let’s look at the highlights of the course.

2. JavaScript syntax

JavaScript syntax, which I’m going to break down into four sections.

directory

2.1 Data Types

2.1.1 Object

2.1.1.1 Object Data Structure

2.1.2 Array Array

2.1.3 String The character String is a String

2.1.4 Number Number

2.1.5 Boolean Indicates the Boolean value

2.1.6 Map mapping

2.1.7 Set collection

2.1.8 NULL/Undefined (2.1.9)

2.2 the control flow

2.2.1 Condition judgment

2.3 the function

2.3.1 definition

2.3.2 Variable scope

2.3.3 Higher-order functions

2.3.4 closure

2.3.5 Special Objects

2.4 Special Objects

2.1 Data Types

There are many types of JavaScript data, of which there are six basic types:

  • 2.1.1 Object

    2.1.1.1 Object Data Structure

  • 2.1.2 Array Array

  • 2.1.3 String The character String is a String

  • 2.1.4 Number Number

  • 2.1.5 Boolean Indicates the Boolean value

  • 2.1.6 Map mapping

  • 2.1.7 Set collection

  • 2.1.8 NULL/Undefined (2.1.9)

I’m separating Array from Object because it’s a very important special Object, and mapping maps and sets are new data types in ES6 that I’ll cover separately.

2.1.1 Object

  • Is a collection of key-value pairs
  • Keys are strings
  • A Value can be of any type
  • Objects are copied into shallow or deep copies
    • Shallow copy: Copies only the memory address of an object, similar to a pointer
    • Deep copy: A complete clone that generates a new object
// define an object
let obj = {hello: 'world'};

// shallow copy
let obj2 = obj;

// deep copy
let obj3 = JSON.parse(JSON.stringify(obj));
Copy the code

Let’s start with objects, which are collections of key-value pairs. **JavaScript objects are very similar to the Python data type Dictionary. Is a data structure used to represent mappings, but it has some limitations. ** One of the big limitations is that the Key can only be a string and the Value can be any data type.

In addition, we need to note that:

Deep and shallow copy in JavaScript, which is a common operation on objects or arrays in JavaScript, needs to be distinguished.

For shallow copies: the newly copied variable stores the memory address of the copied object, and any operation on the newly copied object directly changes the contents of the copied object.

For deep copies: in contrast, the newly copied variable is the overall clone of the copied object, not the memory address. Therefore, there is no connection between the two, and the content of each change will not affect each other.

  • For some reference operations, we often use shallow copies to make it easier to operate.
  • For some operations that require additions, deletions, and changes, such as ToDoList, we need deep copies.
2.1.1.1 Object Data Structure:
// This is an Object
let me = {
    name: 'AI yue".gender: 'male'.age: "secret".nationality: 'Chain'.team: 'AIYC'};// assign attributes
me.title = 'mr';
me.education = 'College';

// get all keys
Object.keys(me)

// get all Values
Object.values(me)

// iterate
for (let key in me) {
    if (me.hasOwnProperty(key)){
        const value = me[key]
    }
}
Copy the code

The above code is the basic operations of the object’s data structure, including how to define, get values, set values, traverse, and so on.

2.1.2 Array Array

  • An array is an ordered collection
  • The value of an array can be of any type
  • Arrays are copied as deep and shallow
    • Congruence with object

An Array is an ordered collection, similar to a List in Python. The value of the array can be any data type, it also has the problem of depth copy, this is the same as the object I talked about above, array add, delete, change and check are listed below.

// This ia an array
let items = [1.2.3.4.5];

// get an item from the array
let index = 1;
items[index];

// set an item value
items[index] = 2;

// get array length
items.length;

// append an item
items.push(6);

// insert an item
items.splice(
    0.// index to insert
    0.// delete count
    0.// item to insert
);

// delete an item
items.splice(
    0.// index to delete
    1.// delete count
);

// iterate
items.map(d= >d);
items.forEach(d= >{
    // do something
})
Copy the code
  • Lookups are done using indexes. The syntax is: items square brackets plus index — items[index];

  • To get the length of the array, just add.length to it;

  • If you want to add an element to the end of the array, you just call Push;

  • If you need to insert an element somewhere, you just call the splice method;

  • To Delete an element, use the same splice method, but specify that the second parameter — Delete count — is not zero, so the splice method can add or Delete elements. Don’t be confused!

  • There are two other ways to iterate over a set of numbers:

    • The first method is a Map
    • The second method is forEach

    The difference between the above two methods is that Map returns a new array, while forEach does not. So we use — Map when we need to operate on an array element and return a new array, and forEach when we don’t need to return

2.1.3 String The character String is a String

  • A string is any type defined by single or double quotes
// This is a string
let str = 'Hello AI Yue Chuang ';
Copy the code

This is similar to many languages, but JavaScript doesn’t distinguish between single quotes and double quotes; (If you’ve learned Python, you know that it’s actually a string (STR) data type in Python.)

As a result, JavaScript specifications are somewhat loose, and we use tools to regulate them, such as ESLint. But the specification of the code is beyond the scope of this column, so I won’t go into it.

# This is a string in Python
str_data = 'AI yue"
Copy the code

2.1.4 Number Number

  • A number is any type that represents a number
// This is a number
let num = 123;
Copy the code

They can be integers or decimals. Note that JavaScript, unlike other languages, does not differentiate between integers and floating-point types. All numeric related types are of type Number.

2.1.5 Boolean Indicates the Boolean value

  • Booleans are types that represent True or False
// This is a Boolean
let bool = true;
Copy the code

Maps and sets are new types in ES6 to address the shortcomings of objects and arrays in ES5.

2.1.6 Map mapping

A map is very similar to an object, except that the Key of the map can be of any type.
  • A set of Key Value pairs
  • Unlike objects, keys can be of any type
// This is a Map
let m = new Map([[1.'first as number'],
    ['1'.'first as strings']]);// get a value from key
m.get(1);

// set a value
m.set(1.1);

// clear all
m.clear()
Copy the code

2.1.7 Set collection

A Set is equivalent to an array that has been de-duplicated
  • Equivalent to an array of non-repeating values

The two data types Map and Set are very useful when used properly — they can save a lot of redundant code.

// This is a set
let s = new Set([1.2.3]);
Copy the code

2.1.8 null null values

  • Equivalent to a “null” value
  • Indicates that the value is null

2.1.9 Undefined

  • Meaning “undefined”
  • Usually used to compare non-existent attributes or values

Note: The next two confusing data types are null and undefined.

Null means that a value is null and not of any other type; Undefined means that the variable is not defined — usually for properties and values that do not exist. The two are conceptually confusing, and in practice I recommend always null for assignments and always three equals signs for comparisons instead of two.

Ps:

The difference between three equals signs and two equals signs: Since JavaScript is a weakly typed language, values of any type can be compared. In the three cases where the equals sign is true, make sure that the values on both sides of the comparison are the same and of the same type. Two equal comparisons convert a data type to a data type and then compare it.

So, from a development point of view: three equals is much more stable than two equals, and I would always recommend three equals over two equals. Of course, some developers may use two equal signs in reverse crawling to confuse each other. In this case, you have to be aware that there are casts between them.

2.2 the control flow

cycle

  • while
  • for
  • Array
    • map
    • forEach
// This is a while for loop
while (a < 10){
    a++;
}

// This is a for loop
for (let i = 0; i < 10; i++){
    console.log(i);
}

// Array can also loop
const arr = [1.2.3];

// map loop
const arr2 = arr.map(d= > d + 1);

// forEach loop
arr.forEach(d= > console.log(d));
Copy the code

I’ll continue to introduce you to JavaScript control flow, which is relatively easy to understand. First, let’s take a look at loops, JavaScript loops, there are three main types: while loops, for loops, and array loops.

  • The while loop is similar to other languages in that it is followed by a judgment condition.
  • Similarly, the for loop takes three conditional parameters
  • Array loops are map and forEach (both of which were covered earlier)

2.2.1 Condition judgment

  • It can be if () {} else {}
  • It could be if () else
  • The intermediate condition is else if
// This is the best
if (a > b) {
    // do something
} else if (a == b) {
    // do something else
} else {
    // do something more
}

// This is ok
if (a > b) alert('ok');
else alert('not ok');
Copy the code

This is JavaScript conditional judgment, if else. It’s very simple and very similar to other programming languages, which I won’t go into here. Just make sure it’s grammatically correct.

2.3 the function

  • 2.3.1 Definition of functions
  • 2.3.2 Variable scope
  • 2.3.3 Higher-order functions
  • 2.3.4 closure
  • 2.3.5 Special Objects

JavaScript function is the focus of this article, because in JavaScript reverse, we will see a lot of function-related skills and methods, please learn carefully

Below, I’ll introduce you to function definitions, variables, scopes, higher-order functions, closures, and special objects, which are very important for understanding JavaScript code. Especially higher-order functions and closures, there are many examples of this in some code confusion.

2.3.1 Definition of functions

  • With the function name
    • function funcName (param) {statement}
    • const funcName = function (param) {statement}
  • No function name (anonymous function)
    • (function (param) {statement} () )
// With function name 1
function funcName1 (param) {
    // do something
    return param;
};

// With function name 2
// const funcName equals an anonymous function
const funcName2 = function (param) {
    // do something
    return param;
};

// Without function name
(function (param) {
    // do something
    returnparam; }) ('Hello AI Yue Chuang ')
Copy the code

There are three types of function definitions, the first two are defined with a function name, and the last one is defined without a function name — that is, anonymous functions.

With function name:

The first definition is the function keyword plus the function name, and then the parameters and function content.

The second way is to define functions in the same way that you define variables. For example, const funcName equals an anonymous function.

There are differences between the two definitions. The first definition uses the function keyword directly — it is a function declaration. In JavaScript function declarations take precedence over everything else, so when the browser loads the code, it loads the function first. Therefore, this definition can be invoked anywhere. In contrast, functions that define variables have a certain order of execution.

If a function is defined as a variable, an error will be reported after the reference, whereas a function declaration will not.

Anonymous functions:

Finally, there are anonymous functions, which are often more common in JavaScript reverse order because they are an effective form of obfuscation. The higher-order functions and closures described later may use anonymous functions.

2.3.2 Variable scope

  • Definition of variables
    • Variables defined by var, const, and let are scoped
    • The variables defined by var work inside their respective functions
    • Variables defined by const and let are block-level scoped
  • Promotion of variables
    • Scans the entire function body, elevating all declared variables to the top of the function
  • Global scope
    • If the var, const, let declaration keyword is not specified to define the variable, the variable will be bound to the global variable Windows
  • Block-level scope
    • Let, const will apply to for, while, etc

Let’s take a look at the scope of variables. In ES5, JavaScript variables were defined mainly by the keyword var, and later in ES6, const and let were added.

  • In the case of var, the scope is also inside the function, while const and let variables are scoped at the block level, as we’ll get to in a moment.

  • Variable promotion is when the JavaScript engine scans the entire function body and promotes all declared variables to the top of the function. Therefore, if a variable defined later is referenced in advance, it will not cause undefined error. In fact, there are many examples of JavaScript variable promotion, you can find information on the Internet to learn about it, deepen your understanding.

  • Global scope means that when no var, const, let, etc declaration is specified, the defined variable is bound to the global variable Windows.

  • Block-level scope means that the scope of a const or let variable is inside a for, while loop and cannot be accessed externally. This has the advantage of increasing the encapsulation of the code.

2.3.3 Higher-order functions

  • define
    • A function that takes another function as an argument is called a higher-order function
  • use
    • The callback
      • Callback
    • An array of operating
      • Filter, sort, map, forEach
function first(a, b, callback) {
    return callback(a, b);
}

function second(c, d) {
    return c + d;
}

first(1.2, second);
Copy the code

Another important aspect of JavaScript functions is higher-order functions, which take another function as an argument and run it inside the function.

So the question is, why do higher-order functions exist?

Before ES6 Promise came out, one of the more important functions was asynchronous operation. I believe many friends who did front-end before 2015 will be familiar with callback function, which was an asynchronous programming standard at that time. However, with the emergence of Promise, async/await and so on, this has gradually been phased out. We’ll talk about that later.

The other important thing is that in the array operation, you need to pass in a callback function to complete the array operation. The above code is an example of a higher-order function. The main function first receives a callback as an argument, takes a and b arguments in the main function, and passes in the result of the callback second as the return value.

If we call this function (first), the result is: 1+2 = 3.

2.3.4 closure

  • define

    • The return value of a function can be a function
    • All arguments and variables are stored in the return function
    • All operation logic is executed when the return function is called (all operation logic is returned when the return function is executed)
  • use

    • Anonymous self-executing functions
    • encapsulation
    • Results the encapsulation
function closureFunc(a, b) {
    return function (i) {
        return Math.pow(a + b, i); }}Copy the code

Closures are also a very important concept in JavaScript, and many JavaScript reverse processes will encounter scenarios that use closures extensively.

There are three main definitions: first, the return value of a function is a function; Second, all arguments and variables are stored in the returned function. Third, all operation logic is returned only when the returned function is executed. (This concept is very similar to Python decorators.) Those of you who are interested will join us in the next installment: Python’s Powerful Decorators

Closures are easy to understand if you are familiar with decorators. What does a closure do?

What do closures do?

In fact, closures can be used for many purposes, but I’ll give you three main points: anonymous self-executing functions, encapsulation, and result caching.

  • First anonymous self-executing function: for example, a piece of code that defines an anonymous function that returns a function and calls that function.
  • Second wrapper: Wrapper closures can hide some of the calculation logic in return functions, which improves code readability
  • Third result caching: Most of the time we do not rush to compute the result of a function, but rather leave it for later execution. Closures are used to cache functions in return functions for later execution. Closures are used in many front-end interviews, the most classic of which is a for loop with a setTimeOut. Why do I always end up with the same number? ** is actually related to the event loop, which I’ll show you later. The correct answer to this problem is to use closures.

Ok, so with all the brain-burning concepts mentioned above, I’m going to introduce you to a relatively simple point, which is special objects.

2.3.5 Special Objects

  • JSON
    • Serialization/deserialization of JSON and objects
    • JSON. Stringfy serialization
    • Json.parse deserialize
  • Date
    • JS time manipulation object
    • new Date(dateString)

There are many special objects in JS, here I will introduce you two. The first is JSON in all caps, which is a static variable that is responsible for serializing and deserializing objects. Json.stringfy is responsible for serialization and json.parse is responsible for deserialization.

You may have noticed that both of these operations were useful earlier when we did deep copies of objects, but this is actually just one way of doing it. Another special object is Date, which handles time and is constructed using the New keyword.

3. JavaScript into order

directory

  • 3.1 Event Loop
  • 3.2 prototype chain
  • 3.3 Asynchronous Programming
  • 3.4 Browser Storage
  • 3.5 cross domain
  • 3.6 Webpack packaging

3.1 Event Loop

  • Definition: the mechanism by which the main thread repeatedly retrieves execution messages and then retrieves execution loops is called an event loop
  • Why an event loop
    • JavaScript is single-threaded
    • An event loop mechanism is needed when handling asynchronous operations
  • Relevant concepts
    • Heap: A large unstructured area of memory where objects and data are stored
    • Stack: Call Stack that stores the tasks to be performed by the main program in this loop
    • Queue: A Queue of events in which fifO is pushed onto the call stack
  • Macro tasks and Micro Tasks
  • Node.js event loop

Many people have probably heard of the concept of an event loop, but what exactly is it?

An event loop is a mechanism by which the main thread repeatedly retrieves execution information and then retrieves execution information repeatedly. This is a mouthful, but we can understand it a little bit. The first thing to remember is that JavaScript is single-threaded, so if every asynchronous operation blocks in the main thread, the program will stall, which is not acceptable. So we need an event loop mechanism to handle these asynchronous operations.

Here are three related concepts:

  • Heap: This is a large, unstructured area of memory used to store objects and data.
  • Stack: The Stack here is actually the call Stack, which is used to store the tasks that need to be executed sequentially by the main program task.
  • Queue: This is an event Queue. The call stack is pushed on a first-in, first-out basis. At the end of each loop, the main program calls the task message in the task queue. The task message is associated with a function, pushing it and its associated synchronization function onto the call stack, and the main program synchronously executes the function on the call stack. When it’s done, it goes through the next loop, which is the JavaScript event loop.

There are two other concepts about event loops: macro and micro tasks, and Node.js event loops. Due to the length of this article, I will not introduce these two concepts. If you are interested, you can search online for related materials and complete them by yourself.

3.2 prototype chain

  • concept
    • prototype
    • __proto__
    • constructor
  • Application scenarios
    • Inheritance, code reuse
  • Will the prototype chain be required when ES6 comes out?

Each function has a prototype property that points to the function’s prototype object. Each new object has a __proto__ property that points to the object’s prototype. Each stereotype has a constructor property pointing to the association’s constructor.

When an instance’s properties are read, if they are not found, they are looked for in the stereotype associated with the object. If they don’t, they look for the prototype of the prototype, all the way to the top.

The main purpose of the prototype chain is to understand inheritance and code reuse in JavaScript code, because before ES6 came out, JavaScript can only use the prototype to encapsulate and inherit objects, understanding the prototype chain helps to understand the entire inheritance and invocation process. But ES6 has a class keyword, equivalent to a class syntax sugar, can be intuitive object-oriented operations.

So, should we understand prototype chains?

My answer is understanding. Because our column is JavaScript anti-crawler (that is, JavaScript reverse), much of the code that needs to be read and manipulated is ES5 code that has been translated by Babel, which probably contains prototype chains. Therefore, it is necessary for us to learn this content. I will not explain it in detail due to the limited space here, please look at the picture examples above and the online materials to understand.

3.3 Asynchronous Programming

  • The Callback function Callback

    • Execute asynchronously in a function by passing in a callback function as an argument
    • Pros: Simplicity
    • Cons: Callback hell
  • Promise

    • Asynchronous solutions appear in ES6

    • An object from which asynchronous operation messages can be obtained

    • Resolve/reject, then/catch

    • Pros: Solves callback hell

    • Disadvantages: code readability is not high

    I mentioned callback functions earlier, but I’ll go into asynchronous programming in more detail. Until ES6 promises came out, we had to use callback functions to solve the asynchronous execution problem. This is simple and intuitive, but one of the major problems is readability, which is called callback hell. Students can take a look at the example of callback hell in the picture below. Is it very difficult to read?

With the advent of Promise in ES6, callback hell is a thing of the past, and asynchronous functions can be executed sequentially using chained calls. Promise is a special object that can get asynchronous action information, and it has resolve + then and Reject + Catch to handle successful and failed callbacks, but it still has the disadvantage of being less readable for asynchronous operations in complex cases.

To address the Promise problem, syntactic sugars like async/await have been introduced in ES8 to help us write more readable code. It is based on Promise, so it needs to understand Promise knowledge. Async is equivalent to a function that returns a Promise, and await can block in function async function, which can greatly improve the readability of code.

However, there is a small disadvantage that parallel asynchronous operations still need to be performed with promise.all. In general, we recommend async/await for asynchronous operations.

We won’t see this syntax in the reverse process, but we need to understand how it works to help us or the reverse process.

ES6 Promise

const makeRequests = () = > {
    return callAPromise()
    	.then(() = > callAPromise())
    	.then(() = > callAPromise())
    	.then(() = > callAPromise())
    	.then(() = > callAPromise())
}
Copy the code

ES8 async / await

async function fetchData() {
    const result1 = await callAp('https://example.com/endpoint1');
    const result2 = await callAp('https://example.com/endpoint2');
    // ...
}
Copy the code

3.4 Browser Storage

  • Cookies
    • It is used to communicate with the server
    • Less storage
  • Local Storage
    • The amount of memory is larger than Cookies
    • Can only store strings
  • Session Storage
    • Only existing with the current Session, closed browser lost
    • Others are the same as Local Storage
  • IndexedDB
    • Equivalent to the SQL database on the browser
    • More storage space
    • Apis are harder to master
Feature Cookies Local Storage Session Storage IndexedDB
Storage Limit ~4 KB ~5 MB ~5 MB Up to half of hard drive
Persistent Data? Yes Yes No Yes
Data Value Type String String String Any structured data
Indexable? No No No Yes

In the crawler process, sometimes we need to get the data stored by the browser. Let’s take a look at the way the browser stores the data.

The first is Cookies, which are the easiest way to store them and are mainly used to communicate with the server because Cookies are brought with each request.

The second type is Local Storage, which is relatively large, but still can only store strings.

The third type is Session Storage, which is similar to Local Storage except that it is lost when the Session closes.

The fourth is IndexedDB, which is the largest storage method and can store data of any structure. The disadvantage is that the API is relatively cumbersome and difficult to master.

3.5 cross domain

  • Definition: Clients communicate with servers of different sources

Js cross-domain here refers to data transmission or communication between different domains through JS, such as requesting data from a different domain with Ajax, or obtaining data from the framework of different domains (IFrame) in the page through JS. Any difference in protocol, domain name, or port is regarded as a different domain.

Two points in particular:

1. If protocols and ports cause cross-domain problems, the “front desk” is powerless;

2. In terms of cross-domain issues, domains are only identified by “the head of the URL” rather than trying to determine whether the same IP address corresponds to two domains or whether two domains are on the same IP address.

The solution

  • CORS
    • Cross-domain resource sharing, a mature solution for solving cross-domain requests
  • JSONP
    • Cross-domain features based on
    • Can only be used for GET requests
  • iframe
    • Display pages from different sources on one page with the
    • Communicate between pages via PostMessage
  • The reverse proxy
    • Keep the client and server on the same source through a reverse proxy

Cross-domain is not something you need to learn in reverse JavaScript. But it will help you understand the data interaction between the browser and the server. Let’s take a look at some common cross-domain approaches.

The first type of CORS is a popular cross-domain solution, called cross-domain resource sharing. It is a mature cross-domain solution, but its disadvantage is that it may expose ports, which has certain security risks.

The second, older JSONP cross-domain approach is based on the way that <script> tags can cross domains, but this approach only supports GET requests and has significant limitations.

The third type of iframe is a cross-domain method that places web pages from different sources on the same page with the <iframe> tag, using PostMessage between pages.

The fourth and last method is a more secure one, which is to use reverse proxy. We can use Nginx or IIS to do reverse proxy for the request route. Let static resources and API use the same resource to achieve the purpose of cross-domain, this way hidden behind the port, high security.

3.6 Webpack packaging

  • purpose
    • Compile and package different types of source files into static files
  • Why use Webpack
    • The front-end technology is complicated and lacks unified management
    • Large projects require modularity
    • New notations such as JSX and TS need to be compiled before they can be used
  • The compiler
  • The plug-in
  • To optimize the

Webpack technology is the inevitable product of the barbaric growth of front-end technology. It is an important way to integrate many technologies together. The purpose of Webpack is to package and compile files of different formats (such as JS, TS, SASS, etc.) into fixed static files.

Why do we use Webpack?

There are three main reasons: the first front-end technology is complicated and lacks unified management; the second large-scale project needs modularization; and the third new technology, such as JS and TS, can only be used after compilation. In addition to Webpack, which requires a specific compiler to be configured, we usually use Babel as the JavaScript compiler. Webpack also provides many plug-ins to support more special features.

Finally, Webpack has a large number of configurations that need to be optimized to make the packaging process efficient and usable, which is a tricky task.

Students who are interested in Webpack packaging can go to the Internet to search the relevant knowledge and do further study.

conclusion

1. Introduction of JavaScript
  • background
  • Relationship with CSS/HTML
  • The development of
2. JavaScript syntax
  • The data type
  • The control flow
  • function
  • Special object
3. JavaScript into order
  • Event loop
  • Prototype chain
  • Asynchronous programming
  • Browser storage
  • Cross domain
  • Webpack packaging

I first gave some background and development introduction to JavaScript, understand the relationship between it and HTML, CSS, and then we also learned about the related syntax, including data types, control flow, functions and special objects, and so on. Finally I introduced the advanced knowledge of JavaScript. Help us understand JavaScript in depth, including event loops, prototype chains, asynchronous programming, browser storage, cross-domain, Webpack packaging. After learning this article, I believe that students have a certain understanding of the basic knowledge of JavaScript, I hope that in the future, you can further study in each point of knowledge, to consolidate your knowledge of JavaScript, which is very helpful to the actual combat courses behind.

This article is over, welcome to pay attention to the public number: AI Yue Chuang. See you next time!