“Just-fe” front-end basic guide collects and collates the basic knowledge needed for front-end development, which is convenient for laying a solid foundation and checking gaps.

04 – JS basis

0. The running mechanism of JS

  • JS is single threaded and can only do one thing at a time
  • As code executes, an execution context is created, and the code runs in the execution context.
  • Different functions are pushed onto the execution stack to wait for the main thread to execute in order
  • When the synchronous code is finished executing, the callback function for the asynchronous event is placed in a different task queue for execution.
  • Macro and micro task queues, based on event loops, push different tasks onto the execution stack for execution.
  • JS event loop, based on task queue, macro task, micro task, only one micro task queue, but can have N macro task queue

0.5 Execution Context

Execution context: An execution context is an abstraction of the context in which JavaScript code is evaluated and executed. Whenever Javascript code is running, it is running in an execution context.

The creation phase of the execution context generates the variable object, establishes the scope chain, and determines that this points to.

Types of execution contexts: global execution context, function execution context, eval execution context

  • Global execution context – This is the default or base context, and any code that is not inside a function is in the global context. It does two things: it creates a global Window object (in the case of the browser) and sets the value of this to equal the global object. There is only one global execution context in a program.
  • Function execution Context – Each time a function is called, a new context is created for that function. Each function has its own execution context, but is created when the function is called. There can be any number of function contexts. Each time a new execution context is created, it performs a series of steps in a defined order (discussed later).
  • Eval function execution Context – Code executed inside the Eval function also has its own execution context, but since Eval is not often used by JavaScript developers, I won’t discuss it here.

1. The closure

An internal function that accesses variables in an outer scope is a closure.

  • Closures only store references to external variables and do not copy their values.
  • These referenced variables are not destroyed until the closure is destroyed.
  • Closure scenarios: decorators, private variables (avoid global variables, achieve encapsulation)
  • Closures make asynchronous tasks such as timers, event handling, and AJAX requests easier.
  • Scope Chain: Each Scope has a reference to its parent Scope.

2. Basic types

  • Original type String, Number, Boolean, undefined, null, symbol,
  • Complex types Object,Function(the latest standard adds Function)
  • Primitive types are stacked, called frequently, and take up a fixed amount of space
  • Complex types are stored in stacks and heaps, with Pointers in the stack and data in the heap

3. The prototype chain

  • Each constructor has a prototype attribute that points to the prototype object
  • The prototype object has constructor pointing to the constructor
  • The instance created by the constructor has _protoThe _ property points to the prototype object
  • _ of the prototype objectproto_ points to _ of the prototype objectprotoObject. Prototype
  • The constructor is also an object, and its _proto_ to the Function prototype
  • Function._proto_ to the Function prototype
  • Object._proto_ to the Function prototype
  • Function.prototype._proto_ to the Object. The prototype
  • Object.prorotype._proto_ 指向 null

Classes are the syntactic sugar of constructors

4. The direction of this

  • We can only determine when this is called and who calls to whom
  • Change this in several ways: call,apply,bind
  • Arrow function this

5. Deep copy and shallow copy

  • Deep copy: JSON parse (JSON. Stringfy ({})), _. CloneDeep ({})
  • Shallow copy: {… }, Object.assign()

6. Event bubbling and event brokering

6.1 Event Bubbling

Browser events are executed through three phases: capture phase – target element phase – bubbling phase.

  • Capture: From outer layer to inner layer Window -> document -> HTML -> body -> target element
  • Bubbling: From inner layer to outer layer

6.2 The third parameter of addEventListener

  • element.addEventListener(event, function, useCapture)
  • The third argument is whether the event is executed in the capture or bubble phase. True: The capture phase is executed. False: perform this operation in the bubble phase.

6.3 Event Proxy

Adding event listeners to each child element below a list would add too many event listeners. Events can therefore be tied to the parent node and listened on as they bubble. Find the element that was actually clicked by target, and you can achieve the desired effect.

6.4 Prevent bubbling

  • Add event.stopPropagation() to child – only to prevent bubbling, not to prevent events themselves
  • Return false in event handler – prevents bubbling and also prevents the event itself (default event)
  • Event.target == event.currenttarget, which makes the element that triggers the event equal to the element that binds the event, and also prevents the event from bubbling;

6.5 Blocking default events

  • event.prevevtDefault()
  • The listening callback returns false

7. Object.defineProperty

Object.defineProperty(object, key, descriptor) // Enumable, writable and different signals are false by default
Copy the code

8. New String (‘ a ‘); String (‘ a ‘); ‘a’

const str = 'a' // string -- primitive data type, stored on a stack, borrowing properties and methods from wrapped objects
const str1 = String('a') // string -- primitive data type, stored on a stack, borrowing properties and methods from wrapped objects
const str2 = new String('a') // object - Wrap object, stack holds heap pointer, heap holds content
str === str1 // true
str === str2 // false
str1 === str2 // fase
Copy the code

9. JSON.stringfy & JSON.parse

JSON.stringfy(object, replacer, space) / / object, (function: (key, value) : any | array [' a, b, c ']), the indentation Spaces
JSON.parse(string[, receiver]) // The converter, if passed, can be used to modify the original value generated by parsing before the parse function returns.
Copy the code

10. Temporary dead zones

Variables with the let keyword (and const) are promoted, but unlike var, they are not initialized. They cannot be accessed until we declare (initialize) them. This is called a “temporary dead zone”. When we try to access a variable before declaring it, JavaScript throws ReferenceError: Cannot access ‘name’ before initialization.

11. Built-in objects

  • Global variable: NaN, undefined
  • Global functions: parseInt(), parseFloat()
  • Global objects: Math, Date, Object, RegExp,

12. Methods for obtaining prototypes

  • obj.proto
  • obj.constructor.prototype
  • Object.getPrototypeOf(obj)

13. Memory leaks

  • Unused global variables
  • Uncleared timer
  • Closure private variables
  • Out-of-dom references: References that are bound to the DOM, but the DOM is removed

14. The arguments object

  • The set of parameter values passed in a function
  • Has length attribute
  • Is not an array
  • You can use the Array. The prototype. Slice. The call (the arguments) into an Array
  • Arrow functions have no arguments objects

15. Functional programming

  • (often abbreviated FP) is the process of building software by writing pure functions that avoid shared state, variable data, and side effects.
  • Functional programming is declarative rather than imperative, and application state flows through pure functions

16. Higher-order functions

A function that takes a function as an input or returns a function

17. Why are functions first-class citizens

In JavaScript, functions not only have everything that traditional functions do (declare and call), but they can behave like simple values:

  • Var func = function(){}
  • The ginseng (function func (x, the callback) {callback (); }),
  • Function (){return function(){}}),

In addition, functions in JavaScript act as constructors of classes and as instances of Function classes.

Regular expressions

Basic grammar

practice

// ab-cd-ef -> abCdEf 
function camelcase(str) {
  return str.replace(/\-\w/g.(v) = > v.replace(/\-/g.' ').toUpperCase())
}
Copy the code

19.Promise

  • The Pormise constructor is executed synchronously, and the THEN method is executed asynchronously

ES new concept

1.Map

  • Map: Similar to an object, but its key can be an object. The normal object key must be a string.
  • Methods: get, set, delete, has, clear, size
  • WeakMap: Key must be an object. Except (null)

2.Set

  • Set: Similar to an array, but no duplicate elements are allowed in a Set. (Can be used for array deduplication).
  • Methods: add, delete, has, clear, size
  • WeakSet: Elements must be objects.

3. The Proxy agent

  • get(target, propKey, receiver): intercepts the reading of object properties, such asproxy.fooandproxy['foo'].
  • set(target, propKey, value, receiver): Intercepts the setting of object properties, such asproxy.foo = vorproxy['foo'] = v, returns a Boolean value.
  • has(target, propKey)Intercept:propKey in proxyReturns a Boolean value.
  • deleteProperty(target, propKey)Intercept:delete proxy[propKey]Returns a Boolean value.
  • ownKeys(target)Intercept:Object.getOwnPropertyNames(proxy),Object.getOwnPropertySymbols(proxy),Object.keys(proxy),for... inLoop to return an array. This method returns the property names of all of the target object’s own properties, andObject.keys()The return result of the object contains only the traversable properties of the target object itself.
  • getOwnPropertyDescriptor(target, propKey)Intercept:Object.getOwnPropertyDescriptor(proxy, propKey)Returns the description object of the property.
  • defineProperty(target, propKey, propDesc)Intercept:Object. DefineProperty (proxy, propKey propDesc),Object.defineProperties(proxy, propDescs), returns a Boolean value.
  • preventExtensions(target)Intercept:Object.preventExtensions(proxy), returns a Boolean value.
  • getPrototypeOf(target)Intercept:Object.getPrototypeOf(proxy), returns an object.
  • isExtensible(target)Intercept:Object.isExtensible(proxy), returns a Boolean value.
  • setPrototypeOf(target, proto)Intercept:Object.setPrototypeOf(proxy, proto), returns a Boolean value. If the target object is a function, there are two additional operations that can be intercepted.
  • apply(target, object, args): Intercepts operations called by Proxy instances as functions, such asproxy(... args),proxy.call(object, ... args),proxy.apply(...).
  • construct(target, args): intercepts operations called by Proxy instances as constructors, such asnew proxy(... args).
// Proxy example
const handler = {
	set: () = > console.log("Added a new property!"),
	get: () = > console.log("Accessed a property!")};const person = new Proxy({}, handler);

person.name = "Lydia";
person.name;
Copy the code

With the Object. DefineProperty contrast

  • Object.definedproperty is used to hijack the properties of an Object, the getter and setter methods of the property, to perform specific operations when the properties of the Object change. Proxy hijacks the entire object.
  • The Proxy will return a Proxy object, we just need to manipulate the new object, andObject.definePropertyCan only be modified directly by traversing object properties.
  • Object.definedproperty does not support arrays, or more specifically, the various apis for arrays, because it is possible to hijack only arry[I] = value, but this hijacking is not meaningful. Proxies can support various apis for arrays.
  • Although object.defineProperty has many drawbacks, it is more compatible than Proxy.

4. The iterator iterators

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).

// Iterator syntax
const obj = {
  [Symbol.iterator]:function(){}
  [Symbol.asyncIterator]: function* () { yield 1 yield 2}}Copy the code

Iterators are iterated by getting a pointer to an iterator that starts before the first piece of data, and then changing the pointer to point to the next piece of data by calling next

Each time next returns an object with two properties

  • Value represents the data to be retrieved
  • Done Boolean value: false indicates that the current pointer has a value, true indicates that the traversal is complete
  • Iterator does three things:
    • To provide a unified and simple access interface for various data structures;
    • To enable the members of a data structure to be arranged in some order;
    • ES6 created a new traversal command for… The of loop is an Iterator interface for… Of consumption.

Traversal process:

  • Creates a pointer object that points to the start of the current data structure. That is, the traverser object is essentially a pointer object.
  • The first call to the next method of a pointer object points to the first member of the data structure.
  • The next call to the next method of the pointer object points to the second member of the data structure.
  • Call the next method of the pointer object until it points to the end of the data structure.

5.Generator

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. Generator Is an Iterator Generator whose return value is an Iterator that can be used for asynchronous calls.

async function* range(start, end) {
  for (let i = start; i <= end; i++) {
    yield Promise.resolve(i); }} (async() = > {const gen = range(1.3);
  for await (const item of gen) {
    console.log(item);
  }
})();
Copy the code

Wechat public number: “egg fungus,” Github: portal

Welcome to