1. Js event flow
When an event is generated by a node, it is propagated in a particular order between the element node and the root node, and is received by all nodes along the path. This propagation process is called DOM event flow.
The event flow describes the order in which events are received from the page.
The event flow consists of three phases :(1) the event capture phase, (2) the target phase, and (3) the event bubble phase
- Event capture: Propagated step by step from document to target element.
- Target phase: The phase in which the actual target node is processing events.
- Event bubbling: Propagates progressively from the target-triggered element up to the Window object.
The addEventListener() method makes it easier to control how events react to bubbling. element.addEventListener(event, function, useCapture);
- The first parameter is the type of the event (such as “click” or “mousedown”).
- The second argument is the function we want to call when the event occurs.
- The third argument is an optional Boolean value that specifies whether event bubbling (false) or event capturing (true) is used.
2. The closure
The concept of closures
Closures are functions that can read variables inside other functions.
Example:
for( var i=1; i<=5; i++) {
setTimeout( function timer() {
console.log( i );
}, i*1000);
} // Output 5 6's
//setTimeout is an asynchronous function that completes the loop first. I is 6, so it prints a bunch of 6's
Copy the code
Use closures to solve:
for (var i = 1; i <= 5; i++) {
(function(j) {
setTimeout(function timer() {
console.log(j);
}, j * 1000);
})(i);
} //1 2 3 4 5(one digit per row)
Copy the code
Closure usage scenarios
- Successful callback to ajax request
- Callback method for event binding
- The delay callback of setTimeout
- Function returns another anonymous function inside the function
- Constructor’s private property
- Calculate the cache
- Function throttling, anti – shake
Pros and cons of closures
Function: calls external variables from inside the function, private properties of the constructor, and extends the life of the variable
Advantages:
- Reads a variable in another function’s scope;
- By keeping these variables in memory at all times, a closure can make the environment in which it was created always exist;
- Encapsulate the private properties and methods of the object, and then access variables in the function by calling closures in the global scope;
Disadvantages: Unable to reclaim referenced variables in closures, prone to memory leaks.
Js event delegate
Event Delegation, also known as Event Delegation, is the Delegation of response events that should be bound to child elements (click, keyDown…) Delegate to the parent element to take on the role of event listener. Event broker works by bubbling events from DOM elements.
Delegate to the parent when an event is triggered.
Advantages:
- Reduce memory consumption
- Dynamically bound events
4. Js is object-oriented
Object Oriented Programming (OOP)
Object-oriented programming is a programming pattern that creates real-world models in an abstract way.
One hallmark of object-oriented languages is the concept of classes, through which you can create any number of objects with the same properties and methods.
Js itself has no class type, but each function has a Prototype attribute. Prototype refers to an object, and when a function is used as a constructor, prototype acts like class.
The three major characteristics
- Encapsulation: Encapsulate objective things into abstract classes, hide the implementation details of properties and methods, and expose only interfaces.
- Inheritance: JS provides the concept of prototype chain, and takes the prototype chain as the main method to achieve inheritance. The basic idea is to use the prototype to make one reference type inherit the attributes and methods of another reference type.
- Polymorphic: Provides a unified interface for entities of different data types.
5. Prototypes and prototype chains
5.1 the prototype
A prototype defines some common properties and methods. New object instances created using the prototype share all the properties and methods of the prototype
A Prototype is an object, through which the property inheritance of the object can be realized. JS objects contain a Prototype internal attribute, which corresponds to the Prototype of the object.
Prototype is an internal attribute of an object that cannot be accessed directly. JS creates objects (normal objects/function objects) with a built-in attribute called __proto__ that points to the object’s Prototype.
5.2 prototype chain
In JavaScript, each object has an internal link to its prototype object.
When an object A calls A method, it will first look for the method from itself. If not, it will look for its own prototype to see if there is such A method. If not, it will continue to look for the prototype of object A’s parent class B, and so on, called the prototype chain. Any level found directly call, no longer look up, if the last is not found error.
constructor
Each stereotype has a constructor property that creates all instances of that stereotype.
6. Html5 uses local storage
cookie
The size of a piece of data cannot exceed 4KB and a maximum of 20 pieces of data can be stored. If the expiration time is not set, the data will disappear after the browser is closed
sessionStorage
Session storage. The size of a session cannot exceed 5M. There is no limit on the number of sessions
localStorage
Local storage is stored in key-value pairs. The size of a pair cannot exceed 5M. There is no limit on the number of pairs.
Fetch record: getItem;
Setting record: setIten;
7. Common Http status codes
-
200 Request succeeded
-
404 requested resource (web page, etc.) not found
-
500 Internal server error
-
301 Permanent redirect. A resource (web page, etc.) permanently moved to another URL indicates that the requested resource has been assigned a new URI and will use the URI to which the resource now refers.
-
302 Temporary redirect. The status code indicates that the requested resource has been assigned a new URI and the user is expected to use the new URI to access it this time.
-
304 Condition when a client sends a conditional request and the server allows the request to access a resource but the condition is not met.
8. Get and POST requests
In a GET request, parameters are placed in the URL, while in a POST request, parameters are placed in the request body. Theoretically, POST is more secure because the URL length cannot exceed 1KB. However, IN a GET request, parameters are placed in the URL.
9. Garbage collection mechanism
Every time a Js program creates a string, array, or object, the interpreter must allocate memory to store that entity. Whenever memory is allocated dynamically like this, it must eventually be freed so that it can be reused, otherwise the JavaScript interpreter will consume all available memory in the system, causing the system to crash.
- Mark and sweep
This is the most common garbage collection method in JavaScript. When a variable enters the execution environment, such as declaring a variable in a function, the garbage collector marks it as “entered”, and when the variable leaves the environment (the function ends), it marks it as “out of the environment”. The garbage collector marks all variables stored in memory at run time and then removes variables in the environment and variables referenced by variables in the environment (closures). Variables that remain marked after this completion are the ones to be deleted.
- Reference Counting (Reference Counting)
Memory leaks are common in lower versions of IE, often due to reference counting garbage collection. The strategy for reference counting is to keep track of how many times each value is used.
When a variable is declared and a reference type is assigned to the variable, the number of references to the value is increased by one; If the value of the variable into another, this is worth reference number minus 1, when the value of citations to 0, show that no variables in use, this value can not be visited, so it can be to take up space, garbage collector will be at run time to clear off the value of the citations of 0 to take up space.
10. Add large numbers, overflow problem
// if the js Number type exceeds 16 bits, the precision of the calculation will be lost
var s1=111111122222
var s2=2222222299999999
var str1=s1.toString();
var str2=s2.toString();
var MaxLength=Math.max(str1.length,str2.length)
var len1=str1.length;
var len2=str2.length;
var tmp=0;/ / carry
var sum=0;
var myStr="";
for(var i=0; i<MaxLength; i++){ sum=Number(str1.charAt(len1-i-1)) +Number(str2.charAt(len2-i-1));
if(sum>9){
sum=sum%10;
tmp=1;
}else{
tmp=0;
}
myStr=sum+myStr;
}
console.log("The results.".Number(myStr));/ / 2222333300011111
Copy the code
11. Shallow copy and deep copy
-
Basic data types: data stored directly on the stack
-
Reference data type features: store the object in the stack reference, the real data is stored in the heap memory
The reference data type stores a pointer on the stack to the starting address of the entity in the heap. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the entity from the heap.
The assignment
When you assign an object to a new variable, you assign the object’s address on the stack, not the data in the heap. That is, two objects point to the same storage space. Any change in the object is the content of the changed storage space.
Shallow copy
A shallow copy creates a new object with an exact copy of the original object’s property values. Properties are primitive types and copy values of primitive types; Properties are reference types and copy memory addresses, so if one object changes the address, it affects the other. Deep copy
A deep copy is a complete copy of an object from the heap, creating a new area of the heap to store the new object, and modifying the new object does not affect the original object. Shallow copy method
- Array.concat()
- Array.slice()
- Object.assign()
// Modifying the new object (array) changes the original object (array)
let arr1 = [1, {num:24}, { name: "koko" }, { age: 23 }];
console.log("The original - arr1", arr1);
let arr2 = arr1.concat();
arr2[2].name = "lolo";
console.log("concat-arr2", arr2);
let arr3 = arr1.slice();
arr3[3].age = 18;
console.log("slice-arr3", arr3);
let arr4 = Object.assign({},arr1);
arr4[1].num = 11;
console.log("assign-arr4", arr4);
Copy the code
Deep copy method
- JSON.parse(JSON.stringify())
Json.stringify converts an object into a JSON string, and json.parse () parses the string into an object. As you go, new objects are created, and the object opens up a new stack for deep copy.
let arr=[1.2, {num:24}, { name: "koko" }];
let arr1=JSON.parse(JSON.stringify(arr));
arr1[2].num=19;
console.log("Primitive array --arr",arr);
console.log("json--arr1",arr1);
Copy the code
- Recursive method to achieve the principle of deep cloning: traversing the object, array until the inside are basic data types, and then to copy
/ / recursion
var obj={
a:1.b: {c:2.d:3},
e: {f:4.g:5}}function deepCopy(obj){
var cloneObject={};
for(let key in obj){
if(obj[key] instanceof Object){
cloneObject[key]=deepCopy(obj[key]);
}else{ cloneObject[key]=obj[key]; }}return cloneObject;
}
var a=deepCopy(obj);// Deep copy the new object
console.log(a);
Copy the code
conclusion
12. Breadth and depth first traversal
Breadth First Search (embossing First Search)
Start from a point, find out its adjacent node into the queue and mark, and then pop up the first node from the queue, find its adjacent node has not been visited into the queue, until all the nodes have been visited the adjacent point; If there are still unaccessed points in the figure, select another unaccessed point and perform the same operation until all nodes in the figure are accessed.
DFS(Deep First Search)
Starting from the current node, mark the current node first, and then look for unmarked nodes adjacent to the current node:
- (1) If the current node does not have a next node, the previous node is returned for DFS
- (2) If the current node has a next node, DFS is performed from the next node
The article quotes the elder picture, in this thanks!