JS based
The principle of the new
- What does New do
- What happens when new returns different types
- The implementation process of handwriting new
Executes a constructor that returns an instance object
- Create a new object
- Make the __proto__ of the new object point to the constructor’s prototype
- Execute the constructor to change the reference to this by calling Apply
- Then make sure you return an object. Otherwise return a new object instead of the this object generated by the new step
There are two branching cases
Constructor that contains a return statement without using new
The new keyword always returns an object after execution
Hand to tear
function create(fn,... args){
var obj = Object.create(fn.prototype)
var res = fn.apply(fn,args)
return typeof res === 'object' ? res : obj
}
Copy the code
Prototype/Prototype chain
__proto__ and prototype relationships: __proto__ and constructor are unique to objects, and the Prototype property is unique to functions
When we access a property of an object, if that property doesn’t exist inside the object, then it will look for that property in its prototype object, and that prototype object will have its own prototype, and so on and so forth, the concept of prototype chain.
-
Prototype: Used to implement object property inheritance. Each JavaScript object contains a __proto__(nonstandard) attribute pointing to its parent (the object’s prototype), accessible from obj.__proto__.
-
Constructor: A function that creates an object through new
-
Instance: An object created by the constructor and new is an instance
Instances point to prototypes via __proto__ and to constructors via constructor
Prototype chain
A prototype chain is made up of prototype objects. Each object has a proto attribute that points to the prototype of the constructor that created the object. Proto connects objects together to form a prototype chain. Is a finite chain of objects that implements inheritance and shared properties
Attribute lookup mechanism: If the attribute cannot be found at this level, it is searched up the prototype chain
Attribute modification mechanism: only the attribute of the instance object itself will be modified. If it does not exist, the attribute will be added. If you need to modify the attribute of the prototype, you can use: b.prototype.x = 2; This, however, causes the properties of all instances that inherit from the object to change.
Each object has a proto attribute that points to the prototype of the constructor that created the object. [[prototype]] is an internal attribute that we can’t access, so use _proto_.
inheritance
Class is syntactic sugar. JS does not have classes
Person instanceof Function
Copy the code
There are really only two of them to remember
- The class inheritance
class Parent {
constructor(value) {
this.val = value
}
getValue() {
console.log(this.val)
}
}
class Child extends Parent {
constructor(value) {
super(value)
this.val = value
}
}
let child = new Child(1)
child.getValue() / / 1
child instanceof Parent // true
Copy the code
At the heart of class inheritance is the fact that extends indicates which parent class it inherits from. And you must call super() in the constructor directory
This is equivalent to borrowing the parent class to construct this, and then adding this attributes to the child class
- The most recommended posture for combinatorial inheritance
function Parent5(){
this.name = 'name'
this.way = 'father'
}
function Child5(){
Parent5.call(this)
this.age = '16'
}
Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5
Copy the code
inheritance
Event mechanism
- The event capture phase has an outside-in-window Document body
- In the target stage
- Events bubble from inside out
The W3C standard is capture and bubble, and the third parameter to addEventListener determines whether the event is registered as capture (true) or bubble (false).
- Event.preventdefault () : Cancel the default action of the event object and continue propagation.
Event.stoppropagation ()/ event.cancelBubble = true: Prevents event bubbles.
Key points:
- Usually we register events using addEventListener, and the third argument to this function can be a Boolean or an object. For the Boolean useCapture parameter, this parameter defaults to false. UseCapture determines whether a registered event is a capture event or a bubble event
- In general, we only want events to fire on the target, and stopPropagation can be used to prevent further propagation of events. StopPropagation is usually thought of as preventing events from bubbling, but it also prevents capturing events. StopImmediatePropagation can also be implemented to block events, but it can also prevent the event target from executing other registered events
The Iterator Iterator
An Iterator is an interface, or a specification. Provides a unified access mechanism for various data structures. The Iterator interface can be deployed on any data structure to complete traversal (that is, processing all members of the data structure in turn).
Each time the next method is called, information about the current member of the data structure is returned. Specifically, it returns an object containing both the value and done attributes. Where, the value attribute is the value of the current member, and the done attribute is a Boolean value indicating whether the traversal is complete.
let arr = [{num:1},2.3]
let it = arr[Symbol.iterator]() // Get the iterator in the array
console.log(it.next()) // { value: Object { num: 1 }, done: false }
console.log(it.next()) // { value: 2, done: false }
console.log(it.next()) // { value: 3, done: false }
console.log(it.next()) /
Copy the code
Manually traverse an object
let obj = {
id: '123'.name: 'Joe'.age: 18.gender: 'male'.hobbie: 'sleep'
}
obj[Symbol.iterator] = function(){
let keyarr = Object.keys(obj)
let index = 0
return {
next(){
return index < keyarr.length ? {
value: {
key: keyarr[index],
val: obj[keyarr[index++]]
}
} : {
done: true}}}}for (let key of obj) {
console.log(key)
}
Copy the code
The Promise tag needs to be improved. The async object returns
When you talk about promise, in addition to the pain points it addresses and the common apis, it’s best to extend eventloop and talk about the execution order of microTasks and MacroTasks. If you look at the source code of Promise, It’s best to talk about how native promises are implemented. The key to Promise is the callback’s two arguments, resovle and Reject. Then there’s the chain call to Promise (promise.then (), where each then is a responsible person).
The core is probably the source code, and how does the promise statement work
This is not very clear
Generator
Generator is a new syntax in ES6 that, like Promise, can be used for asynchronous programming. The Generator functions are a concrete implementation of the Iterator interface. The most important feature of the Generator is that it can control the execution of functions.
I think I can do it. Look at the questions and write the answers. Because async await is the syntactic sugar of this content. It’s more concise
I’m not sure I understand. I’ll give you two examples to figure it out
function *foo(x) {
let y = yield (x + 1)
let z = yield (y / 3)
return (x + y + z)
}
let it = foo(5)
console.log(it.next()) // => {value: 6, done: false}
console.log(it.next(12)) // => {value: 8, done: false}
console.log(it.next(13)) / / = >
// { value: 6, done: false }
// { value: 4, done: false }
// { value: 30, done: true }
Copy the code
function *foo(x) {
let y = 2* (yield (x + 1))
let z = yield (y / 3)
return (x + y + z)
}
let it = foo(5)
console.log(it.next()) // => {value: 6, done: false}
console.log(it.next(12)) // => {value: 8, done: false}
console.log(it.next(13)) / / = >
// { value: 6, done: false }
// { value: 8, done: false }
// { value: 42, done: true }
Copy the code
async/await
Note the relationship between macro tasks and micro tasks
Event loop
Some of the problems I understood before
Macro tasks refer to specific code segments, as shown in the figure
- The default code is executed from top to bottom, and the execution environment is executed via script (macro tasks)
- During code execution, call the timer Promise Click event… It does not execute immediately and needs to wait for the current code to complete
- Queue asynchronous methods into microtasks (immediately) and macro tasks (when time is up or something happens)
- After script execution, all microtasks are cleared
- When the microtask is complete, the page is rendered (not called every time)
Then go to the macro task queue to see if there are any arrivals, and take one of them out and execute it
- After the execution, repeat the above steps
The garbage collection
Recycling is mainly used to mark clear, reference counting
V8’s garbage collection mechanism is based on generational collection, which in turn is based on the generation hypothesis, which has two characteristics: new objects tend to die early, and undead objects tend to live longer. Based on this hypothesis, v8 divides memory into the new generation and the old generation.
Depth copy
Shallow copy occurs in the case of reference type data. Because the address of the data is saved, a shallow copy occurs during replication
- object.assign
let target = {};
let source = { a: { b: 1}};Object.assign(target, source);
console.log(target); // { a: { b: 1 } };
Copy the code
-
Extended operator mode
-
Concat treats arrays as if they were deep copies
-
Slice changes on the original array, as if it were a shallow copy
Throttling and anti-shaking
- Anti-shake to avoid short multiple clicks to send multiple requests to the back end
- Function throttles are events that are repeated multiple times per unit event. It can only take effect once
The code Github library contains it
The Proxy agent
var f = new Proxy(target,handler)
var f = new Proxy(target,{
get: function(target,key){},set: function(target,key,value){}})Copy the code
Function:
- Intercepts and monitors access to objects by external objects
- Validates or manages or preprocesses operations before making complex requests
Ajax
var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');// Compatible with Internet Explorer 6 and later versions
//2: Configure the Ajax request address
xhr.open('get'.'index.xml'.true);
//3: sends a request
xhr.send(null); //
//4: listens for the request and receives the response
xhr.onreadysatechange=function(){
if(xhr.readySate==4&&xhr.status==200 || xhr.status==304 )
console.log(xhr.responsetXML)
}
Copy the code
An array of
Ways to change yourself
Based on ES6, there are nine methods that change their values: POP, Push, Reverse, Shift, sort, splice, unshift, and two new ES6 methods, copyWithin and Fill
- Pop,push add and remove from the right
- Shift unshift Shift removed from the left
- Sort (func) is actually a function that defaults to smaller on the left and larger on the right
<! - flashbacks - >var points = [40.100.1.5.25.10];
points.sort(function(a,b){return b-a});
Copy the code
-
Splice modifies the array to add or remove elements
-
- array.splice(index,howmany,item1,….. ,itemX)
-
- Index is the start of the subscript and howmany is the number of operations
-
Slice does not modify the original array
-
array.slice(start, end)
-
reverse
-
fill array.fill(value, start, end)
-
copyWithin
-
- array.copyWithin(target, start, end)
-
- The copyWithin() method is used to copy elements from one specified location in the array to another specified location in the array.
ES7
- Concat Join Slice toString toLocaleString, indexOf, lastIndexOf, unstandardized toSource, and includes
- concat
-
- arr.concat()
- join
-
- Array to string
- toString
-
- An array is converted to a string to split it
- toLocaleString()
- indexof
- The String.indexof (searchValue,start) array also works
- includes
- Whether or not to include returns true false
Traversal method
ForEach, every, some, filter, map, reduce, reduceRight, and ES6 new methods Entries, find, findIndex, keys, values
forEach
- array.forEach(function(currentValue, index, arr), thisValue)
every
- array.every(function(currentValue,index,arr), thisValue)
- The every() method is used to check whether all elements of an array meet the specified criteria (provided by a function).
- One returns false and ends
some
- The some() method is used to check whether elements in an array satisfy the specified condition (provided by the function).
filter
- The filter() method creates a new array of elements by checking all eligible elements in the specified array.
map
- The map() method returns a new array whose elements are the values processed by the call to the original array element.
reduce
- That’s what we were able to do before
- array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduceRight
- Starting on the right, this part is exactly what it means
Array and string methods
- Img – repo. Poetries. Top/images / 2021…
- Poetries1. Gitee. IO/img – repo / 20…
- Poetries1. Gitee. IO/img – repo / 20…
entries
var array = ["a"."b"."c"];
var iterator = array.entries();
console.log(iterator.next().value); // [0, "a"]
console.log(iterator.next().value); // [1, "b"]
console.log(iterator.next().value); // [2, "c"]
console.log(iterator.next().value); // undefined. If the iterator is at the end of the array, undefined is returned
/
Copy the code
find
- The find() method returns the value of the first element of the array that passes the test.
- array.find(function(currentValue, index, arr),thisValue)
findIndex
- The findIndex() method returns the index of the first element of the array that passed the test.
The keys() method is used to create an iterable from an array that contains the array keys.
Values () value
Understand JS class arrays
Function arguments;
Using getElementsByTagName/ClassName/Name for querySelector HTMLCollection gains NodeList
- Arguments is the collection of parameter values passed in a function. Because it has the length property, but it’s not an array. There are no built-in methods in arrays such as forEach, Reduce,filter, and Map
Array.prototype.slice.call(arguments);
Copy the code
Object.prototype.toString.call(arguments)
Copy the code
HTMLCollection
HTMLCollection is simply an interface to the HTML DOM object. This interface contains a collection of DOM elements that are retrieved. The returned type is an array object, and if typeof is used, it returns ‘object’. It is up to date, and as the DOM in the document changes, so does it.
NodeList
Class array object, can traverse through the subscript, passing parameters using img – repo. Poetries. Top/images / 2021… The callee attribute points to itself
A method that converts an array of classes to an array
function sum(a, b) {
let args = Array.prototype.slice.call(arguments);
// let args = [].slice.call(arguments); // It works the same way
console.log(args.reduce((sum, cur) = > sum + cur));
}
Array.prototype.slice.call(arguments);
Array.prototype.concat.call([],arguments);
// ES6 destruct assignment
function sum(a, b) {
let args = Array.from(arguments);
console.log(args.reduce((sum, cur) = > sum + cur));
}
sum(1.2); / / 3
function sum(a, b) {
let args = [...arguments];
console.log(args.reduce((sum, cur) = > sum + cur));
}
sum(1.2); / / 3
function sum(. args) {
console.log(args.reduce((sum, cur) = > sum + cur));
}
sum(1.2); //
Copy the code
Array flattening
- recursive
- reduce
- .
- Flat arr. Flat ([depth]) The default value is 1. Depth indicates the depth of an array that can be expanded. Infinity infinite depth
Through this online site regexper.com/ regular analysis into easy to understand visual logical brain map