• [2021] Front direction: Review of summer internship refers to north (Top)
  • [2021] Front direction: Review of summer internship Refers to north (middle)

JavaScript article

Theory of ch1 –

Data type correlation

Data type classification

JS data types can be divided into two categories: basic data types, reference data types

  • Basic data types: Number, String, Boolean, Undefined, Null, (symbol, bigint)
  • Reference data types: Function, Object, Array

Data type differences

  • The differences between the two types are as follows: The basic type is stored in the memory stack; The reference type stores the data address in the memory stack and the actual data content in the heap.
  • A typical example is as follows:
let a = [1.2], b = a
b.push(3)
console.log(a===b) // true
Copy the code

Since a and B save the same address, the change to the data content will not affect the equality of A and B.

How to determine the data type

  1. typeof
type The results of
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol "symbol"
Functin "function"
Any other Object (Object, Array) "object"

Typeof can accurately identify basic types, but cannot distinguish reference types.

  1. instanceof

Generally used to determine the reference type.

[1.2] instanceof Array //true
Copy the code

The following error occurs when determining a simple type:

var str = 'hello world'
str instanceof String // false

var str1 = new String('hello world')
str1 instanceof String // true
Copy the code
  1. Object.prototype.toString

Can do accurate identification.

Object.prototype.toString.call(99) //"[object Number]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call({}) //"[object Object]"
Copy the code

Prototypes and prototype chains

First to a picture, to give an intuitive understanding (personally think than the elevation of the book to be easy to understand ha ha ha) don’t dislike the word ugly ha ha ha, with the plate painting.

The prototype

You can see that #605 and #809 are prototypes.

Where is the prototype?

The window Object mounts a number of built-in functions: Object, Array, Function, and so on, which we call constructors. Each constructor has a Prototype property, and prototype refers to the prototype we’ve been talking about.

What is the prototype?

The essence of a prototype is an object. It provides common methods and properties for the corresponding types. Array.prototype provides Array unique push and pop methods. Function.prototype: Provides the call method specific to Function types.

How do I find prototypes?
  • using__proto__Properties (not recommended)
[1.2.3].__proto__ === Array.prototype  //true
Copy the code
  • usingObject.getPrototypeof(instance)
Object.getPrototypeOf([1.2= = =])Array.prototype  //true
Copy the code

Prototype chain

Why is it that we can call push, pop and other methods when we never declare methods without an array?

const arr = []
arr.push(1) / / [1]
Copy the code
Step by step to find

If js cannot find the corresponding method on the current object, it will search down the prototype chain layer by layer. Such as:

const arr = []
arr.push(1)	/ / [1]
arr.hasOwnProperty("keys")	//true
arr.sayHi()	//Uncaught TypeError: arr.sayHi is not a function
Copy the code
  • There is no push method on arR; Call the push method on array. prototype if it exists along the prototype chain.
  • No hasOwnProperty on arR; Array.prototype (hasOwnProperty); Continue down the stereotype chain. Since the “array stereotype” is essentially an Object instance, the “array stereotype” is Object. Prototype.
  • There is no such method on arR, array prototype, or object prototype; whileThe object prototype is the end of the prototype chain Object.getPrototypeof(Object.prototype) === nullTherefore, this method does not exist.

In JavaScript OOP

What does New do

function Person(name){ this.name = name }
Person.prototype.say = function() { console.log( this.name )}
let p = new Person("Lee")
Copy the code
  1. Create an empty objectlet obj = {}
  2. Obj’s __proto__ refers to the constructor’s ptototype
    obj.__proto__ = Person.prototype
    Copy the code
  3. Perform the Person call (obj)
  4. Return Person. Call (obj) if the return value res is of type object; Otherwise, return obj.

Parasitic combinatorial pattern

function Person(name){ this.name = name }
Person.prototype.say = function() { console.log( this.name )}
function Children(age) { 
	Person.call(this); 
    this.age = age
}
Children.prototype = Object.create(Parent.prototype,{constructor: Children})
/* equivalent to child.prototype. __proto__ = person.prototype; Child.prototype.constructor = Child; * /
Copy the code

The class model

class Person{
	constructor(name){
    	this.name = name
    }
    say(){ console.log(this.name) }
}

/* extends is equivalent to child.prototype. __proto__ = person.prototype; Child.prototype.constructor = Child; * /
class Children extends Person{
	constructor(name, age){
    	super(name)	// Equivalent to parent-.call (this,name);
    	this.age = age
    }
}
Copy the code

AJAX

  • Full name: async JavaScript and XML JS obtain XML update pages from the server through asynchronous communication

Native ajax:

const xhr = XMLHttpRequest()
xhr.open('GET'.'/')
xhr.onreadystatechange = () = >{
	if(xhr.readyState===4 && xhr.statusCode===200) {console.log(xhr.responseText)
    }
}
xhr.send()
Copy the code

Ajax Lite:

const xhr = XMLHttpRequest()
xhr.open('GET'.'/path? query=x')
xhr.onload(() = >{console.log(xhr.responseText)})
xhr.onerrer(() = >{console.log('error')})
xhr.send()
Copy the code

Event mechanism

Event capture: father before son, first outside before inside. Event bubble: son before father, inside before outside.

  • To stop bubbles: event.stopPropagation()
  • AddEventListener (“click”, fn, false) : The third argument is whether to execute during the capture phase. The default is false, which is executed in the bubble phase.

Ch2 – Operating mechanism

Variable ascension

  • The reason why variable promotion is needed is because of the JS mechanism: first compile, then run.
  • During compilation, variables and functions are stored in the variable environment, and the default value of variables is set to undefined. During code execution, the JavaScript engine looks for defined variables and functions from the variable environment.
  • If, at compile time, there are two function definitions with the same name, the last one will be stored in the variable environment.
  • Function promotion has a higher priority than variable promotion and is not overridden by variable declaration, but by variable assignment.
showName()
var showName = function() { console.log(2)}function showName() { console.log(1) }
showName() // 1 , 2/ *** is equivalent to *** /function showName() { console.log(1)}var showName	Function promotion is not overridden by variable declarations
showName()
showName = function() { console.log(2)}Copy the code

Call stack and execution context

  • Every time a function is called, the JS engine compiles the corresponding function code and creates the execution context (including variable environment object, lexical environment object, this reference) and pushes it onto the call stack. The CODE is then executed by the JS engine
  • After the function is executed, the memory occupied by variables in the function is cleared, and the execution context is loaded onto the stack.
  • A stack overflow occurs when the number of execution contexts in the call stack reaches a certain number.

scope

Definition: Scope is the area in a program where variables are defined.

Global scope

Js can access global-scope variables from anywhere

Function scope

Variables or functions defined inside a function can only be accessed inside the function. The function is destroyed at the end of execution.

Block-level scope
  1. Inside of the functionvarDeclared variables are stored at compile timeThe variable environmentThe inside.
  2. throughletDeclared variables are stored at compile timeLexical environmentIn the.
  3. In block-level scope within a function, variables declared by a let are stored in a centralized area and pushed to the top of the lexical environment object. (A small stack structure is maintained within the lexical environment.)

4. Temporary dead zone: in the block-level scope, if the variable is usedlet / constDeclaration, an error will be reported if the variable is used before the declaration.

The scope chain

Lexical scope:

Scope is determined by where functions are declared in the code and is static. The scope chain is determined by lexical scope.

  • Each function declaration creates a function declaration object whose [[scope]] property points to the execution context in which the function is declared.

  • Each variable environment contains an outer attribute, which points to the external execution context (the context corresponding to the [[scope]] attribute in the function’s declaration object).

  • The outer property of the variable environment in a global context is null, meaning that the global context is the end of the scope chain.

Scope chain definition:

  1. Definition: Essentially a list of Pointers to an execution context.
  • Function: Ensures orderly access to all variables and functions that the execution environment has access to. Variables and functions in the outer environment can be accessed through the scope chain.

Variable search method:

  • Lexical environment object top stack
  • ==> Lexical environment object bottom stack
  • ==> Variable environment object
  • ==> Execution context corresponding to outer
  • ==> Search by scope chain until global execution context: outer is null

closure

  • define:Closure = function + reference to its lexical environment. (OFFICIAL MDN definition)

Since the function object [[scope]] property of a function declaration records the characteristics of the outer lexical environment, you can return a function to preserve variables in the current execution context.

  • USES:
    1. The first use of closures is to enable variables inside a function to be accessed from outside the function. By using closures, we can access variables inside the function externally by calling the closure function externally. We can use this method to create private variables.
    2. Another use of closures is to keep a function object in a function context that has finished running in memory because the [scope] property of the function object retains a reference to the lexical environment, so the lexical environment is not reclaimed.
    3. Callback functions like setTimeout.

This usage

  • Arrow function: does not create an execution context and does not have its own this.

    let obj = {
        num: 1.prin: function(){
            // The parent scope holds the parent this
            setTimeout(() = >{
                console.log(this.num);
            },1000)
        }
    }
    
    obj.prin()	/ / 1
    // This is actually the application of closures.
    Copy the code
  • Binding loss: When an implicit binding acts as a callback, a binding loss occurs.

    let user = {
      firstName: "John".sayHi() {
        alert(`Hello, The ${this.firstName}! `); }};setTimeout(user.sayHi, 1000); // Hello, undefined!
    Copy the code

ch3 – ES6

The difference between let and var

  1. Let block level scope
  2. Let does not have variable promotion (function and var have variable promotion)
  3. There is a temporary dead zone and an error will be reported if used before the variable name
  4. Let does not allow repeated claims
  5. Var variables declared in the global context become properties of window; Let not
  6. The var variable is registered in the variable environment object of the execution context, and the let const variable is registered in the lexical environment object of the execution context.

promise

My blog: juejin.cn/post/692429…

Deconstruction assignment

  • Swap variable [a,b] = [b,a]

  • Processing parameters

    function (args){
    	const {num,sum} = args
    }
    Copy the code

String

  • Template string

    ` name:${name}`
    Copy the code
  • Includes, startsWith, and endsWith

Array

  • Array.from

  • arr.fill

  • arr.includes

  • arr.flat

    arr.flat(n)	//n is the number of layers to be leveled
    [1[2[3]]].flat(Infinity)	// Flatters the infinite layer to flatters a one-dimensional array
    Copy the code

Object

  • Object. Assign (target, obj1, obj2) Shallow copy
  • Object.getPrototypeof( obj )

Ch4 – programming

JS native methods commonly used

Array change method: make changes on the original array

  • Sort () : You can pass in a function to compare, passing in two values before and after, and swapping the positions of the two arguments if the return value is positive.
  • Reverse () : Switches the order
  • Splice () : Insert/delete element method
  • Push, pop, shift, unshift

Array replacement: return a new array from the original array

  • Concat () : concatenation of arraysArr. Concat ([2, 3])
  • Slice () : used to return a slice from an arrayArr. Slice (0, 5)
  • The indexOf() and lastIndexOf() iterative methods
  • Every (), some(), filter(), map(), and forEach() methods: process the array item and return the result
  • Reduce method: Consolidate the values in the array into a single value.
    Let arr = [1, 2, 3] arr. Reduce ((independence idx sum, v, a) = > sum + v * v, 0) / / 14Copy the code

Object

  • Object.create(obj) : Creates an Object modeled after obj
  • Assign (target, obj1, obj2) : Merges obj1 and obj2 into target

EventLoop

  • Check out my personal blog :juejin.cn/post/692416…
  • Two reference drawings are attached:



Depth copy

Shallow copy

A shallow copy is not complete if the properties on the object are still of a reference type.

//method 1
let a = { id:1 }
let new_A = Object.assign( {}, a )
//method 2
let a = { id:1 }
letb = {... a}let a = 1
let b = a
Copy the code

Deep copy

Recursively make a full copy

  1. JSON.parse(JSON.stringify( obj ))
  2. By recursive functions
    let deepClone = (obj) = >{
    	if (typeofobj ! = ="object" && typeofobj ! = ="function") throw new Error(a);else {
    		let newObj;
    		if (Array.isArray(obj)) newObj = [...obj];
    		elsenewObj ={... obj};for (let i in newObj) {
      			if (typeofnewObj[i] ! = ="object") continue;
      			else newObj[i] = deepClone(newObj[i]);
    		}
    	return newObj;
    }
    Copy the code

Array to heavy

  • indexOf + reduce
let fn = arr= > arr.reduce((account,v) = >{
	if(account.indexOf(v)===-1) account.push(v)
},[])
Copy the code
  • indexOf + filter
let fn = arr= > arr.filter((v,index) = >arr.indexOf(v)===index)
Copy the code
  • Set
let fn = arr= > [...new Set(arr)]
Copy the code
  • Map (uniqueness of key)
let fn = arr= >{
	let map = new Map()
    arr.forEach(v= >map.set(v,true))
    return [...map.keys()]
}
Copy the code

Write in the last

After the last one was written, the company’s project suddenly got busy and delayed for a long time. Before period of time review enthusiasm some cool down. To be honest, I feel very confused about the road ahead. I don’t know if every front-end er knows and is committed to what they want. But here’s what I know now: I’m truly passionate about the front end, so I tell myself to stick with it and work on it.

Hope to encourage everyone! Come on together!