Today, there are also very hard to earn cat food money

If there are mistakes or deficiencies in the article, please understand and help me to point out, thank you very much


Data type and storage mode

The original type is divided into seven types, which are:

boolean number string undefined null symbol bigint

There are two types of objects:

Object Function

The primitive type is stored on the stack, and the object type is stored on the heap, but its reference address remains on the stack


More comprehensive:

Basic types:

Number, Boolean, String, null, undefined, symbol (ES6 new), BigInt (ES2020)

Reference type: Object

Object subtypes: Array, Function

NaN

NaN means “not a Number,” but it is of type Number, and NaN is false when compared to anything, even itself.

typeof NaN === ‘number’

symbol

  • Can be used to represent a unique variable to prevent naming conflicts

  • By using the method of symbol are not regular (in addition to the Object. GetOwnPropertySymbols) traversal, so can be used to simulate the private variables

  • Mainly used to provide traversal interface, layout of symbol. Iterator objects can use for···of loop, can be unified processing data structure. After the call, a traverser object is returned, which contains a next method. After the next method is used, two return values, value and done, indicate the current execution position of the function and whether the traversal is complete.

False value

  • undefine

  • null

  • false

  • +0, -0, NaN

  • “”

0.1 + 0.2 =?

When the two numbers are added, the mantissa will be converted to binary first. When 0.1 and 0.2 are converted to binary, the mantissa will have an infinite loop, and then the order calculation will be carried out. JS engine truncates binary, resulting in loss of accuracy.

var let const

ES6 added the let command to declare variables. Its use is similar to var, but the declared variable is only valid within the code block in which the let command resides.

Var:

The “variable promotion” phenomenon occurs when the var command is used, that is, the variable can be used before the declaration and its value is undefined. Variables can be defined repeatedly. (It is now rarely used in development).

let:

Variables need to be declared before they can be used. The declared variables have block-level scope.

Let does not allow the same variable to be declared twice in the same scope.

Const:

Const must be assigned immediately after the declaration or an error will be reported.

Const Simple types cannot be changed once declared. Pointers to complex types (arrays, objects, etc.) cannot be changed. Internal data can be changed.


Let, const

Let usage scenario: variable, used instead of var.

Const is used when constants, anonymous functions, and arrow functions are declared.

this

This refers to the object on which the function is called. In general, this is the Global object and can be called as a method. The value of this changes depending on where the function is used.

This refers to whoever calls it, and in the global context, to the Window object.

scope

  • Global scope

  • Function scope

  • Block-level scope

ES5 has only global and functional scopes, not block-level scopes, which leads to a lot of irrational scenarios.

In the first scenario, the inner variables may override the outer variables.

In the second scenario, loop variables used to count are exposed as global variables.

Note that ES6 block-level scopes must have braces; if there are no braces, the JavaScript engine assumes that there is no block-level scope.

The scope chain

In javascript learning, execution environment and scope are two very important and basic concepts.

The execution environment defines other data that variables or functions have access to, and determines their respective behavior. Each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in this object. Although the code we write cannot access this object, it is used behind the scenes by the parser as it processes the data.

When code is executed in an environment, a scope chain of variable objects is created. The purpose of scope chains is to ensure orderly access to all variables and functions that the execution environment has access to. The entire scope chain is a linked list of Variable objects at different execution positions constructed according to the rules.

At the front of the scope chain is always the variable object of the environment in which the code is currently executing. The next variable object comes from the containing (external) environment, and the next variable object comes from the next containing object. This continues to the global execution environment; The variable object of the global execution environment is always the last object in the scope chain.

Prototype chain

The prototype

Each instance object has a constructor property pointing to its constructor.

Each function object (including the constructor) has a Prototype property that points to the function’s prototype object. The constructor property of the prototype object points to the function itself.

Each object has a [[prototype]] private property that points to its constructor’s prototype object, but this property is not accessible. Some browsers (such as Chrome) provide __proto__ attributes for accessing [[prototype]] private attributes

The constructor attribute points to Function and the __proto__ attribute points to function.prototype. Because constructors are created using new Function, they are all instance objects of Function, including Function and Object

The prototype property of all constructors except Object has its __proto__ attribute pointing to Object.prototype. The __proto__ attribute of Object’s prototype property points to NULL

Prototype chain

All objects have a __proto__ attribute, and that __proto__ attribute points to a prototype object. Because a prototype object is also an object, and this prototype object also has a __proto__ property, we call this relationship a prototype chain

When you need to access an object’s properties, you start with the object and return to it if it can be found.

If not, the object’s __proto__ attribute points to the prototype object, and if it can be found, returns there. If not, look up the prototype object until the __proto__ attribute points to NULL, the top of the prototype chain

If all stereotype objects on the stereotype chain do not have this property, undefined is returned.

OK, that may be a bit of an exaggeration, but to summarize, the prototype chain is based on an Object, with the _proto_ link as the chain up to Object.prototype.

Solving cross domain problems & homology

Before understanding the cross-domain problem, understand the same-origin policy first. What is the same-origin policy? The same protocol, domain name, and port must be the same.

  • Cookie, LocalStorage, and IndexDB cannot be read

  • DOM not available

  • AJAX requests cannot be sent

There are many ways for the front-end to solve cross-domain problems. I usually use the following 1 or 2 methods:

  • Nginx reverse proxy

    Advantages of reverse proxy: 1. All requests pass through the proxy server first to protect network security. 2. Load balancing, forwarding requests to servers under less pressure. 3. You can do some middle-tier Settings, such as caching static resources.Copy the code
  • Set changeOrigin in the proxyTable to true in config

  • Jsonp (GET requests only)

  • CORS

  • postMessage

  • node

  • webSocket

  • iframe

call apply bind

Call (), apply(), bind() are methods on function.prototype. All functions can be called with this as their first argument.

The call method can execute the calling function, pointing this to the first argument, and passing all subsequent arguments to the calling function.

The all() method is similar to apply() except that call() takes a list of parameters, while apply() takes an array of parameters.

In non-strict mode, if the first argument to call() and apply() is null or undefined, then this refers to the window global variable.

Bind returns methods.

Conclusion:

Call (), apply(), and bind() can all be used to change the this pointer and implement inheritance;

The difference between call() and apply() is that the parameters are different. If you want to express the corresponding relationship between parameters and arguments, use call().

Bind () returns a new function that can be called later, while apply() and call() are called immediately and return results

Characteristics of the arrow function

  • Use => instead of function, simple syntax

  • Without binding this, the this inside the arrow function always points to the object at which it was defined. (Built functions do not create their own this, but inherit from the upper level of their scope.)

  • Call Apply Bind is not supported

  • Unbind arguments (normal functions get arguments passed in via arguments)

  • Support nested

  • Arrow functions cannot be used as constructors; there is no prototype property

JS commonly uses built-in objects and methods

Array Array object, Math method, String method, Date method

Array Array object

push()

Adds one or more elements to the end of the array and returns the new length of the array.

unshift()

Adds one or more elements to the array header and returns the new length of the array

pop()

Removes the last element at the end of the array and returns the deleted element

shift()

Removes the first element of the array and returns the deleted element

Concat () (yes but not necessary, learn about deconstructing assignment)

Array merge, return a new array, the original two arrays will not change

join()

Returns each element of the array as a new string concatenated with the specified character

splice()

This method removes a given number of elements from a specified location, inserts the desired elements at that location, and returns a new array of the deleted elements

slice(start,end)

Intercepts the contents of the copied array at the specified position, returning the new array, without changing the original array

IndexOf (Where to start to query elements)

(To query the element, where to start the query) position is the subscript

Array.from(array-like list)

Converted to an array

LastIndexOf (search element, where to start search)

Look backwards and forwards

arr.sort()

Sort only numbers up to 10

forEach() map()

Through the array

some()

Checks if there are elements in the array that meet the criteria, returning true if there are, false if there are none

every()

Check whether all elements in the array meet the criteria. If one element does not meet the criteria, jump directly. If all elements meet the criteria, return true

filter()

Filter array, returns a new array that meets the requirements

reduce()

The first bit of the array is traversed, the 0th bit is not traversed, and the subscript starts at 1

Array.isArray()

Judge array

Math methods

Math.floor()

Take down the whole

Math.ceil()

Take up the whole

Math.round()

rounded

Math.random()

The random number

Math.abs()

Take the absolute value

String String method

charAt()

Gets the character of the subscript position

charCodeAt()

Converts characters at subscript positions to Unicode encoding

String.fromCharCode()

Converts Unicode encoding to a string

str.concat()

Concatenation string, effect equivalent to concatenation +

IndexOf (), lastIndexOf ()

The indexOf the search character is the same as the indexOf the array

replace()

Replace, like splice() in arrays; Replace does not modify the content of the original character, and returns a new string that has been modified. If two identical elements appear, only the element that was found for the first time is modified

slice(start,end)

Slice (starting at and ending before the subscript) intercepting copy strings are allowed to have negative values, which indicate backwards to forwards

Substr (starting with subscript, truncating length);

Split (separator)

Converts a string to an array by separating it with a delimiter

The reverse ();

Array elements in reverse order or reverse order, this is an array method

The date object

Javascript event Loop/Event Loop/JS execution mechanism; Macro task, micro task

Let’s talk about single-thread and multi-thread before we talk about event loops

• Single thread: When a program is executed, the path of the program is arranged in sequential order. The first one must be processed before the next one can be executed.

• Multi-threading: Multi-threading refers to multiple execution streams in a program, that is, multiple different threads can run simultaneously in a program to perform different tasks, that is, a single program is allowed to create multiple threads of parallel execution to complete their respective tasks.

Then look at macro tasks and micro tasks. In JavaScript, tasks are divided into two types: macrotasks, also known as tasks, and microtasks.

Macroqueue, MacroTask. Callbacks from asynchronous tasks are placed in the Macro Task Queue, waiting to be called later:

  • SetTimeout and setInterval

  • requestAnimationFrame

  • I/O

  • UI rendering

Microqueues, microtasks. The callbacks of other asynchronous tasks in turn enter the Micro Task Queue, waiting to be called later:

  • Promise.then

  • Object.observe

  • MutationObserver

Order of execution:

  1. Execute global Script synchronous code, some of these synchronous code are synchronous statements, some are asynchronous statements (such as setTimeout, etc.), encounter asynchronous code according to the above task divided into the corresponding queue;

  2. After executing the global Script code, the call Stack is emptied;

  3. Remove the callback task at the beginning of the microtask queue from the microtask queue and put it into the call Stack for execution. After execution, the length of the MicroTask queue decreases by 1.

  4. Continue fetching the task at the top of the queue, place it on the call Stack, and so on until all the tasks in the MicroTask Queue have been executed. (i.e. clear the microtask queue. Note: If a microtask is created during execution, it will be added to the end of the queue and executed during this cycle.)

  5. When all tasks in the MicroTask Queue are completed, the MicroTask Queue is empty and the call Stack is empty.

  6. Remove the task at the head of the macroTask queue and add it to the Stack for execution.

  7. After the execution, the call Stack is empty.

  8. Repeat steps 3-7;

  9. .

In simple terms, thread synchronization code in asynchronous tasks hang division to the corresponding task queue, thread synchronization code execution is completed, empty task queue, micro tasks to empty, empty execution stack, start executing macro task, after perform the task a macro view the task queue and a clean, then continues executing macro task cycle in turn.

JavaScript is a single-threaded scripting language, which cannot handle multiple tasks at the same time. Therefore, the concept of asynchronous events comes into being. Event Loop refers to a mechanism of browser or Node to solve the problem that JavaScript will not block when running in a single thread, which is also the principle of asynchronism that we often use.

How browsers work

Refer to this article on browser principles

HTTP HTTPS HTTP2

HTTP / 1.1

  • Head of line blocking

    Although HTTP/1.1 protocol can send multiple requests on the same TCP connection, but the multiple requests are sequential, the first request must be processed before the response to the next request. If the first request is particularly slow, all subsequent requests need to be queued.

  • TCP connection number limit

    A browser can create a maximum of six to eight TCP connections for a domain name. If ten requests are sent to a page at the same time, the next two to four requests can only be sent after the first six to eight requests are returned. Domain name sharding comes into being. Allocating resources to different domains (which can be secondary subdomains) solves the limitation, but abusing domain sharding does not work either, since each TCP connection is time-consuming.

  • The Header content is extensive, sometimes exceeding the response content, and many fields are repeated each time.

  • HTTP/1.1 is a text protocol transport and is not secure enough.

New features of HTTP2 over HTTP /1.1 include:

  • MultiPlexing, single long connection, binary format transmission, request priority setting

  • Header compression

  • The Server pushes Server Push

HTTPS

  • Encrypted HTTP

ajax axios

ajax :

  • Asynchronous JavaScript and XML

  • The core uses the XMLHttpRequest object

  • Callback hell occurs when multiple requests appear in sequence

axios :

  • Not native

  • It can be used not only on the client side, but also on the NodeJS side

  • Axios can also intercept in the request and response phases

  • Based on Promise objects

Javascript recycle mechanism

Garbage collection can be implemented in two ways, namely, token scavenging and reference counting

Tag cleanup: Variables are marked “in” when they enter the execution environment and “out” when they leave the execution environment. Variables marked “in” cannot be reclaimed because they are in use, whereas variables marked “out” can be reclaimed

Reference count: Counts the number of times a reference type variable has been referenced since it was declared. When the count is 0, the variable is reclaimed.

A memory leak

A memory leak is memory that is no longer needed and, for some reason, cannot be released.

Memory leaks can be caused by:

  • Global variables cause memory leaks

  • Undestroyed timers and callback functions cause memory leaks

  • Closures cause memory leaks

  • DOM references cause memory leaks

A method to determine an array

  • object.prototype.toString.call()

    You can use Instanceof to distinguish user-defined object types

  • instanceof

    Check whether the prototype of the type can be found in the prototype chain of the object

  • Array.isArray()

Array to heavy

  • Use a double for loop to iterate over a set of numbers, O(n^2)

  • In ES6 we can use the Set data structure for de-duplication

  • Using filter, the essence of de-weighting is to filter the array according to the unique characteristics of the data. Filter can be filtered exactly, so it is consistent with the behavior of de-weighting

  • Use Reduce to remove weight

  • Use the filter

Es6 new features

  • Variable declaration const let scope block

  • Arrow function

  • Template string

  • Class class

  • Object and array deconstruction (especially useful)

  • The Spread/Rest operator

inheritance

Prototype chain inheritance

The relationship between constructors, stereotypes, and instances: Each constructor has a stereotype object, each stereotype object contains a pointer to the constructor, and each instance contains a pointer to the stereotype object.

The essence of inheritance is copying, that is, rewriting a prototype object and replacing it with an instance of a new type.

Borrow constructor inheritance

Using a parent class constructor to enhance a child class instance is equivalent to copying an instance of the parent class to a child class (without using a stereotype).

Disadvantages:

  • Only instance properties and methods of the parent class can be inherited, not stereotype properties/methods

  • Unable to reuse, each subclass has a copy of the parent class instance function, affecting performance

Combination of inheritance

Combining these two methods is called combinatorial inheritance. The inheritance of prototype attribute and method is realized by prototype chain, and the inheritance of instance attribute is realized by borrowing constructor technique.

Type conversion

Converting a value from one type to another is often called a type conversion, and this is what is shown; The implicit case is called a cast.

Casts in JS always return scalar primitives such as strings, numbers, and booleans, not objects and functions.

The casting is divided into implicit casting and display casting.

ToString

It handles non-string-to-string casts:

  • null —> “null”

  • undefined —> “undefined”

  • true —> “true”

For ordinary objects, unless its own definition, the toString () (Object. The prototype. The toString () returns the value of [[Class]] internal attributes, such as “[Object Object]”. But when an object has its own toString() method, stringification calls that method and uses the return value.

JSON stringing

  • The utility function json.stringify () also uses ToString when serializing JSON objects into strings

  • For most simple values, JSON stringification and toString() have roughly the same effect

  • All safe JSON values can be stringified by json.stringify ().

  • Unsafe JSON values include: undefined, function, symbol, and objects that contain circular references, where undefined, function, and symbol are ignored when stringify() returns null in arrays.

  • If you want to stringify an object with an invalid JSON value, or if some value in the object cannot be serialized, you need to define the toJSON() method to return a safe JSON value.

  • You can pass json.stringify () an optional argument, replacer, which can be an array or a function, to specify which properties are processed during object serialization; Another optional argument, space, is used to specify the indent format of the output, or, if a positive integer, the number of characters to indent at each level.

ToNumber

Sometimes you need to use non-numeric values as numbers, such as math operations; That’s where ToNumber comes in;

Where true is converted to 1, false to 0, undefined to NaN, and null to 0

Objects (including arrays) are first cast to the corresponding primitive type value, and if a non-numeric primitive type value is returned, it is then cast to a number following the above rules.

The conversion process checks to see if the value has a valueOf() method. If a primitive type value is present and returned, that value is used for the cast. If not, the return value of toString() is used (if present) for the cast. If neither returns a base type value, a TypeError error is generated

ToBoolean

Values in JavaScript can be divided into two categories:

  1. A value that can be cast to false

  2. other

These are false values:

  • undefined

  • null

  • false

  • +0、 -0、 NaN

  • “”

Theoretically everything except the list of false values is true.

SetInterval and setTimeout

SetImmediate, as defined in the official documentation, is called after the completion of an Event Loop.

SetTimeout is executed by calculating a delay time.

However, it was also mentioned that if the two operations were performed directly in the main process, it would be difficult to guarantee which would fire first.

Because if the main process registers two tasks first, then the code takes more than seconds to execute when the timer is already in the callback state.

So the timer is executed first, and then the Event Loop is completed, and then setImmediate is executed.

forEach map filter

  • The filter function is used to filter all elements that meet the criteria. If true, it returns a new array

  • Map function: a function that processes each element in the original array and returns a new array.

  • ForEach: performs a callback forEach valid item in the array, in ascending order. Deleted or uninitialized items are skipped

pass

  • ForEach and Map can do similar things

  • ForEach, Map, and filter can modify the original array

  • ForEach has no return value, map has a return value, filter has a return value

You can read another piece of my article

closure

  • JavaScript Advanced Programming describes it this way:

Closures are functions that have access to variables in the scope of another function;

  • The Definitive JavaScript Guide describes it this way:

Technically speaking, all JavaScript functions are closures: they’re all objects, and they’re all associated with a scope chain.

  • JavaScript you Don’t Know describes it this way:

Closures occur when a function can remember and access its lexical scope, even if the function is executed outside the current lexical scope.

Closure applications:

  • Implementing public variables

  • You can do caching (storage structure)

  • You can implement encapsulation and privatize attributes

  • Modular development to prevent contamination of global variables

Disadvantages of closures:

Variables referenced by closures are not reclaimed while the closure exists => memory leak

Capture process event bubbling

The event bubbling

The execution order of the event flow, capture phase => target phase => bubbling phase. Bubbling from the inside out.

I

, the event defined on the div, when I click on the span it will trigger the event bound on the span, and then it will trigger the event on the outside div, and that’s bubbling.

The bubbling phase is the process from the target to the Window object. Events are bubbling by default. When the parent element adds a listening event, an event on the parent element is triggered when the child element is clicked. This is a typical bubbling.

Capture phase

In contrast to event bubbling, events occur from the outermost layer up to the most concrete element.

Webpack packaging principles

  • Read the webPack configuration parameters

  • Start the Webpack, create the Compiler object, and start parsing the project

  • Parsing starts from the entry file and pours into the dependent module. Recursively traverses, forming a dependency tree

  • Use corresponding Loader to compile dependent module files of different file types and convert them into JS files.

  • Along the way, WebPack publishes subscriptions, throws hooks, and the WebPack plug-in can intervene in the output by listening for these key event nodes and performing plug-in tasks.

If the throttle

Just read my article