HTML, CSS related

Html5 new features, semantic

  • Header Nav main article section Aside footer
Semantic meaning as the name implies, semantic HTML5 refers to the reasonable and correct use of semantic tags to create page structures, such as header,footer and nav. The function of this tag can be intuitively known from the tag, rather than abusing div. The advantages of semantics are: the code structure is clear, easy to read, easy to develop and maintain and other devices (such as screen readers) to render web pages according to semantics. Good for search engine optimization (SEO), search engine crawlers copy code with different weights based on different tagsCopy the code

Browser rendering mechanics, redrawing, rearrangement

Web page generation process:

  • HTMLTo be parsed by an HTML parserDOM
  • cssIs parsed by the CSS parserCSSOM The tree
  • In combination withDOMTrees andCSSOMTree to generate a render tree (Render Tree)
  • Generate layout (flow), that is, all nodes of all render trees are planar composited
  • Draw the layout (paint) On the screen

Rearrangement (also known as backflow): When a DOM change affects the element’s geometry (the position and size of the DOM object), the browser needs to recalculate the element’s geometry and place it in the correct position in the interface, a process called rearrangement. Trigger:

  1. Add or remove visible DOM elements
  2. Element size changes — margins, padding, borders, width, and height

Repainting: The process of redrawing an element when its appearance is changed without changing its layout. Trigger:

  • element-alteringColor, background, box-shadowAttributes such as

Rearrangement optimization suggestions:

  1. Separate read/write operation
  2. Style set modification
  3. The cache needs to be modifiedDOMThe element
  4. Try to only modifyPosition: absoluteorfixedElement has little effect on other elements
  5. Animation startGPUSpeed up,translateuse3Dchange

The transform does not redraw because the transform is a composite property. When you animate a composite property, a composite layer is created. This allows animation elements to be rendered in a separate layer. When the content of the element has not changed, there is no need to redraw it. The browser creates the animation frame by recomposing it.

CSS box model

All HTML elements can be thought of as boxes, and in CSS, the term “box model” is used for design and layout. The CSS box model is essentially a box that encapsulates the surrounding HTML elements, including: margins, borders, padding, and actual content. The box model allows us to place elements in the space between other elements and the borders of surrounding elements.

CSS style priority

! important>style>id>class

What is BFC? What are the layout rules of the BFC? How do I create a BFC? Landing the application?

BFC stands for Block Formatting Context. BFC is a concept of CSS layout, which is an environment where elements inside do not affect the elements outside. Layout rules: Boxes are the object and basic unit of CSS layout. A page is composed of several boxes. The element type and display attribute determine the type of the Box. Different types of boxes participate in different Formatting contexts. Display: inline-block position: Absolute Application: 1. Margin overlap can be prevented when belonging to different BFC. 2. Adaptive multi-column layout

DOM and BOM objects

The Browser Object Model (BOM) refers to the Browser Object Model. You can access and operate the Browser window. Using the BOM, developers can move Windows, change text in the status bar, and perform other actions that are not directly related to the content of the page. Enable JavaScript to “talk” to the browser. DOM (Document Object Model) refers to the Document Object Model, through which you can access all the elements of an HTML Document. DOM is a W3C (World Wide Web Consortium) standard. The DOM defines the standard for accessing HTML and XML documents: “The W3C Document Object Model (DOM) is a platform – and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents.” The W3C DOM standard is divided into three distinct parts:

  • The coreDOM– Standard model for any structured document
  • XML DOM– Standard model for XML documents
  • HTML DOM– Standard model for HTML documents

What is the XML DOM? The XML DOM defines the objects and attributes of all XML elements, as well as the methods to access them. What is the HTML DOM? The HTML DOM defines the objects and attributes of all HTML elements, as well as the methods to access them.

JS related

Js data types, Typeof, Instanceof, type conversions

  1. String, number, Boolean, null, undefined, object(function, array), symbol(ES10 BigInt)
  2. typeofMainly used to determine the data type of the return valueString, Boolean, number, function, object, undefined.
  3. instanceofDetermines whose instance the object is.
  4. nullRepresents an empty objectundefinedRepresents a variable declared in scope but not assigned

Closure (high frequency)

A closure is a function that has access to a variable in another function’s scope.

Closures occur when a function can remember and access its lexical scope,

Even if the function is executed outside the current lexical scope — JavaScript you Don’t Know

  • Closure purpose:

    1. The ability to access the lexical scope in which a function is defined (preventing it from being recycled)
    2. Privatization variable
    3. Simulate block-level scopes
    4. Create a module
  • Disadvantages of closures: Function variables can be kept in memory, and too many closures can cause memory leaks

Prototype, prototype chain (high frequency)

Prototype: The __proto__ property inherent in an object that points to the object’s Prototype property.

Prototype chain: When we access a property of an object, if the property does not exist inside the object, it will look for the property in its prototype object, which in turn will have its own prototype, and so on and so on, the concept of prototype chain. The end of the prototype chain is usually Object.prototype, so that’s why our new Object can use methods like toString().

Features: JavaScript objects are passed by reference, and each new object entity we create does not have a copy of its own prototype. When we modify the stereotype, the objects associated with it inherit the change.

This refers to the new keyword

This object is an attribute in the execution context that refers to the object on which the method was last called. In global functions, this equals window, and when the function is called as an object, this equals that object. In real development, the direction of this can be determined by four invocation patterns.

  1. Function calls, when a function is called directly as a function that is not a property of an object,thisPoints to a global object.
  2. Method call, if a function is called as a method of an object,thisPoint to this object.
  3. Constructor call,thisPoint to thisnewNewly created object.
  4. The fourth isApply, call and bindAll three methods can display the this pointer to the specified calling function.applyThe parameters are arrays,callAccept a list of arguments, ‘bind’Method returns an object by passing in an object this A new function that binds the passed object. Of this functionthisPoint to besides useIt will be changed when it’s new, and it won’t be changed otherwise.

new

  1. First, a new empty object is created
  2. Sets the prototype of the object to functionprototypeObject.
  3. Let the function of thethisPoint to the object and execute the constructor code (add attributes to the new object)
  4. Determine the return value type of the function and, if it is a value type, return the created object. If it is a reference type, an object of that reference type is returned.

Scope, scope chain, variable promotion

A scope is responsible for collecting and maintaining a series of queries made up of all declared identifiers (variables) and enforcing a very strict set of rules that determine access to these identifiers by currently executing code. (Global scope, function scope, block level scope). A scope chain is a process of looking up a variable from the current scope until it finds the global scope. If it doesn’t, it gives up. This layer by layer relationship is the scope chain.

Inheritance (including ES6), multiple inheritance modes

(1) The first method is to implement inheritance in the way of prototype chain. However, the disadvantage of this method is that when the data of reference type is contained, it will be shared by all the instance objects, which is easy to cause the confusion of modification. Also, you cannot pass parameters to supertypes when creating subtypes.

(2) The second method is to use the borrowed constructor method, which is realized by calling the constructor of the supertype in the function of the subtype. This method solves the disadvantage of not passing parameters to the supertype, but it has one problem is that it cannot realize the reuse of function methods. And the method subtypes defined by the supertype stereotype are not accessible.

(3) The third method is combinatorial inheritance, which is a way to use a combination of stereotype chains and borrowed constructors. Inheritance of attributes of a type is achieved by borrowing constructors, and inheritance of methods is achieved by setting the stereotype of a subtype to an instance of a supertype. This solves the problem of using the two patterns separately, but since we prototyped the subtype using an instance of the supertype, we called the superclass constructor twice, resulting in many unnecessary attributes in the subtype stereotype.

(4) The fourth way is the original type inheritance, the main idea of the original type inheritance is to create a new object based on the existing object, the principle of implementation is to pass an object to the function, and then return an object with this object as the prototype. The idea of inheritance is not to create a new type, but to implement a simple inheritance of an Object. The object.create () method defined in ES5 is an implementation of the original type inheritance. The disadvantage is the same as the prototype chain approach.

(5) The fifth method is parasitic inheritance. The idea of parasitic inheritance is to create a function to encapsulate the inheritance process by passing in an object, then making a copy of the object, then extending the object, and finally returning the object. This process of extension can be understood as inheritance. The advantage of this inheritance is to implement inheritance on a simple object if the object is not of our custom type. The disadvantage is that there is no way to reuse the function.

(6) The sixth method is parasitic combinatorial inheritance. The disadvantage of combinatorial inheritance is that instances of supertypes are used as prototypes of subtypes, resulting in the addition of unnecessary prototype attributes. Parasitic composite inheritance uses a copy of the stereotype of the supertype as the stereotype of the subtype, thus avoiding the creation of unnecessary attributes.

EventLoop

JS is single-threaded, in order to prevent a function the code behind the blocked the execution time is too long, so will try to press the synchronization code into execution stack, in turn, push the asynchronous code into the asynchronous queue, asynchronous queue is divided into macro task queue and task queue, because the macro task queue execution time is longer, so the task queue to priority has been the task queue. Then, MutationObserver, and setImmediate setTimeout setInterval for macro tasks

Native ajax

Ajax is a method of asynchronous communication that retrieves data from the server and partially refreshes the page. Process:

  1. createXMLHttpRequestObject;
  2. callopenMethod passes in a three-parameter request method(GET/POST), URL, synchronous asynchrony (true/false);
  3. Listening to theonreadystatechangeEvents, whenreadystateReturns at 4responseText;
  4. The send method is called to pass the parameters.

Event bubbling, capture (delegate)

  • Event bubbling is when an event of some kind is fired on an object, if the object is bound to an event, then the event is fired, and if not, propagated to the object’s parent object, which eventually fires the event.
  • Event delegation essentially leverages the browser event bubbling mechanism. Since the event is uploaded to the parent node during the bubbling process, and the parent node can obtain the target node through the event object, the listener function of the child node can be defined on the parent node, and the listener function of the parent node can uniformly handle the events of multiple child elements, which is called event proxy.

Event.stoppropagation () or the ie method event.cancelBubble = true; // Prevent events from bubbling

ES6

  1. The new symbol type represents a unique value that defines a unique object property name.
  2. Const /let are used to declare variables that are non-repeatable and have block-level scope. There is a temporary dead zone, that is, there is no variable lift. (const is generally used to declare constants);
  3. Destruct assignment of variables (including arrays, objects, strings, numbers and bools, function parameters), residual operators (… rest);
  4. Template string (${data});
  5. Extension operators (arrays, objects);
  6. Arrow function;
  7. Set and Map data structures;
  8. Proxy/Reflect;
  9. Promise;
  10. Async functions;
  11. Class;
  12. Module syntax (import/export).

Vue

Briefly describes the MVVM

MVVM is short for Model-view-ViewModel, which is the evolution of Controller from MVC to ViewModel. The Model layer represents the data Model, the View represents the UI component, and the ViewModel is the bridge between the View and the Model layer. The data will be bound to the ViewModel layer and automatically rendered to the page. The ViewModel layer will notify the ViewModel layer to update the data when the View changes.

What is your understanding of the VUE lifecycle?

Each Vue instance is created through a series of initializations. Vue lifecycle hooks are functions that are triggered when a certain stage or condition is reached in order to complete some action or event

  • The create phase: The vue instance is createdbeforeCreate: Before creation, data in data and methods has not been initializedcreatedData contains a value but is not mounted
  • Mount stage: Vue instances are mounted to real DOM nodesbeforeMount: can initiate server requests to go to datamounted: Dom can be manipulated
  • The update phase: Triggers component re-rendering when data in the vue instance changesbeforeUpdate updated
  • Destroy stage: The vue instance was destroyedbeforeDestroyMethods can be manually destroyed at this point before the instance is destroyeddestroyed

Computed with the watch

The watch attribute listener is an object, the key is the attribute to be observed, and the value is the corresponding callback function. It is mainly used to monitor the change of some specific data, so as to carry out some specific business logic operations, and monitor the change of attributes. It needs to be used when asynchronous or expensive operations are performed when data changes

The results of attributes computed are cached, and when the attributes on which the computed function depends do not change, the results are read from the cache when the current function is called. Unless recalculated, functions that use computed primarily as attributes must return the final result for computed efficiency, which is preferred

Usage Scenario Computed: Used when an attribute is affected by multiple attributes, for example, shopping cart billing function Watch: used when one data affects multiple attributes, for example, searching data

The role of key in V-for

  1. keyIs mainly used to compare whether each node in the virtual DOM is the same node more efficiently.
  2. Vue in patchKey is a necessary condition to determine whether two nodes are the same. When rendering a list,key is usually a unique identifier, so if you do not define key,VueThe two nodes can only be considered to be the same, even if they are not, which leads to frequent updates of elements that make the wholepatchProcess is relatively inefficient, affecting performance;
  3. As can be seen from the source code, Vue determines whether two nodes are the same mainly by their key and element type, so if the key is not set, its value isundefined, may always think that these are two identical nodes and can only do update operations, which results in a large number of DOM update operations, which is obviously not desirable.

Communication mode of VUE components

Parent-child component communication

Parent -> sub – props, sub -> parent $on, $emit ‘get parent component instances parent, parent, parent, children Ref get instance methods Provide, inject’ But it’s often used when writing component libraries

Sibling communication

Prototype.$Bus = new Vue() Vuex

Cross-level component communication

$listeners Provide, attrs, inject

Commonly used instructions

  • V-if: determines whether to hide.
  • V-for: data loop out;
  • V-bind :class: to bind a property;
  • V-model: implements bidirectional binding

Implementation principle of bidirectional binding

When a Vue instance is created, Vue iterates over the properties of the data option, turning them into getters/setters with Object.defineProperty and internally tracking the dependencies, notifying the properties of changes when they are accessed and modified. Each component instance has a corresponding Watcher program instance, which records properties as dependencies during component rendering and then, when setters for dependencies are called, tells Watcher to recalculate, causing its associated components to be updated.

The implementation of the V-Model and how it works?

  1. vueThe bidirectional binding is an instructionv-model, you can bind a dynamic value to a view, and changes in the view can change the value.v-modelIs syntactic sugar, which by default corresponds to:The value and @ input.
  2. usev-modelIt can reduce a lot of tedious event handling code, improve development efficiency, and make the code more readable
  3. Typically used on form itemsv-model
  4. Native form items can be used directlyv-modelTo use it on a custom component, bind values within the component and handle input events
  5. I have done tests and the output containsv-modelThe component rendering function of the template finds that it will be converted to a binding of the value property and an event listener that will update the corresponding variable in the event callback, indicating that the magic is actually done by the vue compiler.

The realization of the nextTick

  1. nextTickisVueProvides a global viewAPIIt will be next timeDOMA deferred callback is performed after the update loop is complete and is used after the data has been modified$nextTick, you can get the updated in the callbackDOM;
  2. Vue is executed asynchronously when updating the DOM. As long as I’m listening for changes in the data,VueA queue is opened and all data changes that occur in the same event loop are buffered. If the samewatcherIf triggered more than once, it will only be pushed into the queue once. This eliminates duplicate data during buffering to avoid unnecessary calculations andDOMOperation is very important.nextTickMethod adds a callback function to the queue, ensuring that it is not called until the previous DOM operation is complete.
  3. For example, when I’m doing something, I use nextTick, pass in a callback function, and perform DOM operations in it;
  4. I know a little bit about itnextTickImplementation, it will be incallbacksPut in the function that we passed in, and usetimerFuncCall them asynchronously, and the preferred asynchronous would bePromise. This makes me understand why it is possible to be innextTickseedomOperation result.

Vnode understanding, Compiler and patch process

Export function vnode (){return {tag:'div', children: 'span', attr:'', text:' Hello! '}} copies the codeCopy the code

The whole process after new Vue

  • initProxy: scoped proxy that intercepts data within a component that accesses other components.
  • initLifecycle: Establishes parent-child component relationships, adding attributes and lifecycle identifiers to the current component instance. Such as[Math Processing Error]parent,parent,refs,$children,_isMountedAnd so on.
  • initEvents: Adds a listener to the event passed by the parent, which is created by the listener, and the child component creates the event and the child component listens
  • initRender: declares [Math Processing Error]slots and slots and createElement(), etc.
  • initInjectionsInject data and initialize Inject. It is generally used for deeper communication between components.
  • initState: Major) Data responsivity: initialization status. A lot of options to initialize the summary: data, the methods, props, computed and watch.
  • initProvide: Provides data injection.

Consider: why inject first and then provide?

A: First, the data from the grandparent should be combined with the current instance’s data, so be sure to inject data at the top of InitState. 2. The data injected from above must also be injected into the current component because it is passed on to future generations.

Vm.[Math Processing Error]mount(vm.mount(vm.options.el) : mount the instance.

Keep – the realization of the alive

Purpose: implement component cache

Hook functions:

The 'activated' component is called after rendering. The 'deactivated' component is called after destroying the copy codeCopy the code

Principle: Vue. Js internally abstracts DOM nodes into vNodes. The cache of keep-Alive components is also based on Vnodes rather than directly storing DOM structures. The pruneCache and pruneCache components are cached in the cache object, and vNodes are removed from the cache and rendered when needed.

Configuration properties:

Include string or regular expression. Only components with matching names are cached

Exclude A string or regular expression. Any component with a matching name will not be cached

Max number, maximum number of component instances that can be cached

Implementation principles of VUex and VUE-Router

Vuex is a state management library developed specifically for vue.js applications. Key Concepts:

  • state(Single state tree)getter/MutationShow committed changesstate
  • The Action is similar to MutationTo submitMutation, can contain any asynchronous operation.
  • module(When applications get big and complex, break them downstoreFor a specificmoduleModule)

What do you think of the diff algorithm in Vue?

Rendering the real DOM in JS is very expensive. For example, if we modify some data, rendering directly to the real DOM will cause the whole DOM tree to be redrawn and rearranged. Is it possible to update only the small piece of DOM we modify and not the whole DOM? At this point, we need to generate the virtual DOM according to the real DOM. When the data of a node of the virtual DOM is changed, a new Vnode will be generated. Then, the new Vnode will be compared with the old Vnode, and the difference will be directly modified in the real DOM, and then the value of the old Vnode will be changed to the new Vnode.

The process of diff is to call the patch function, compare the old and new nodes, and patch the real DOM while doing so. When the diff algorithm is used to compare the old and new nodes, the comparison only takes place at the same level. In the patch method, tree-level comparison is performed first: delete old Vnode if new Vnode does not exist; add new Vnode if old Vnode does not exist; perform diff update if old Vnode exists. When it is determined that the DIff algorithm needs to be performed, compare two Vnodes, including three types of operations: Attribute update, text update, update child nodes Old and new node has child nodes, then the child nodes for the diff operation, called updatechidren if no child nodes and the new old node has child nodes, clears out the old node text content, and then to the new child node If there is no child node, a new node and the node has child nodes, If all children of the node are removed, the text is replaced when the old, new and old nodes have no children

UpdateChildren Extracts Vch, the child of Vnode, and oldCh, the child of oldVnode. OldCh and vCh each have two starting and ending variables, StartIdx and EndIdx. Their two variables are compared with each other in a total of four ways. If none of the four comparisons match, if the key is set, the comparison will be performed with the key. During the comparison, the variable will move towards the middle, and the comparison will end as soon as StartIdx>EndIdx indicates that at least one of the oldCh and vCh have been traversed.

What Vue performance optimizations have you done?

The coding phase minimizes data in data, adding getters and setters to data, Watcher v-if and V-for can't be used together. If you need to use V-for to bind events to each element, use the event broker. SPA page uses keep-alive cache components. Use V-if instead of V-show key to ensure unique use of routing lazy loading, asynchronous component Shaking prevention, throttling third-party modules on demand import long list scrolling to visual area dynamic loading images lazy loading In the case of loading third-party modules using CDN, multithreading, happypack, splitChunks, and remove common files, optimize user experience, PWA can also use cache (client cache, server cache) optimization, server enable GZIP compression, etc. Copy the codeCopy the code

Do you know what’s new with Vue3? What impact will they have?

  • Performance improvement

Smaller, faster support for custom renderers Supports tree shaker optimization: an optimization that removes useless code at packaging time supports Fragments and cross-component rendering

  • API changes

Template syntax remains 99% unchanged native support for class-based components, Rewriting the virtual DOM without any compilation and stage features is designed with TypeScript’s type inference in mind and can expect more compile-time hints to reduce runtime overhead. Optimized slot generation can render parent and child components separately, raising the static tree to reduce rendering costs Proxy-based observer mechanism saves memory overhead

  • Incompatible IE11

Detection mechanism is more comprehensive, accurate, efficient, more debugable response tracking

How does implementing a bidirectional binding Proxy compare to Object.defineProperty?

  1. 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.
  2. The Proxy returns a Proxy Object and we only need to manipulate the new Object, whereas Object.defineProperty can only be modified by iterating through Object attributes.
  3. 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.
  4. Although object.defineProperty has many drawbacks, it is more compatible than Proxy.

React

1. React keys. Compare nodes at the same level.

Keys are an auxiliary identifier used by React to track which elements in a list were changed, added, or removed. Copy the codeCopy the code

2, Your understanding of virtual DOM and diff algorithms, implement the render function

The virtual DOM is essentially a JavaScript object that is an abstract representation of the real DOM. When the state changes, record the difference between the old tree and the new tree and finally update the difference to the render function in the real DOM:

  1. According to thetagNameGenerate the parent tag, readprops, set the properties,If you have the contentTo set upInnerHtml or the innerText.
  2. If there are child elements, the recursive call traverses the child elementsrenderMethod to add the generated child elements in turn to the parent element and return the root element.

How do React components communicate with each other?

  1. Parent component, parent -> child directly usedProps, son -> fathercallbackThe callback
  2. Non-parent component, publish-subscribe modelEventThe module
  3. If the project is complexRedux, MobxAnd so on global state management management library
  4. Context Api contextWill make component reusability worse

Context provides a way to pass data across the component tree without manually adding props for each layer of components. Component composition is sometimes a better solution than context if you just want to avoid passing properties through layers. 5. Component composition Disadvantages: It can complicate high-level components

4. How to parse JSX

Call the react. createElement function to create the object copy codeCopy the code

5. What kinds of life cycle are there and what things are done at what stage? Why scrap some life cycles?

ComponentWillMount, componentWillReceiveProps, componentWillUpdate in 16 version is rejected, in 17 version will be deleted and you need to use the prefix UNSAVE_ use, purpose is backward compatibility.

6. Optimization methods for React

  • Code level:

Use return NULL instead of CSS display: None to control node display hiding. Keep as few DOM nodes as possible on a page at a time.

  • The props and state data is as flat as possible.

ShouldComponentUpdate and PureComponent to avoid too many render functions; Render minimizes the number of new variables and bind. Should try to flatten the props and state, pass only the props that Component needs. If you pass too many, or too many layers, it adds to the data in shouldComponentUpdate, pass Component as props

  • Code volume:

Use babel-plugin-import to optimize the introduction of business components, implement on-demand loading using SplitChunksPlugin to split common code using dynamic import, lazy loading React components

7. Several ways to bind this

The bind/ arrow function copies the codeCopy the code

8. Understanding of Fiber

React Fiber is a browser-based single-threaded scheduling algorithm. Copy the codeCopy the code

9. Is setState synchronous or asynchronous

  1. setState“Asynchronous” only in synthesized events and hook functions, synchronous in native events and setTimeout.
  2. setState“Asynchronous” does not mean that the internal implementation of asynchronous code, in fact, the execution of the process and code are synchronous, but the call order of the synthesized event and hook function is before the update, so that the updated value cannot be immediately obtained in the synthesized event and hook function, which forms the so-called “asynchronous”. Of course, the callback in the second parameter setState(partialState, callback) can get the updated result.
  3. setStateBatch update optimization is also based on “asynchronous” (composite event, hook function). Batch update will not be performed in native event and setTimeout. In “asynchronous”, if the same value is setState multiple times, the batch update strategy of setState will overwrite it and take the last execution. If multiple setState values are set at the same time, they will be merged and updated in batches.

Redux, react-redux

The implementation process of Redux

The user page Action triggers an Action, and the Store calls the Reducer with two parameters: the current State and the received Action. The Reducer returns the new State. Every time the state is updated, the view triggers a re-rendering based on the state.

React-Redux:

Provider: Encapsulates the entire application from the outside and passes the Store to the Connect module. Connect:

  1. Wrap the original component, willstateandactionthroughpropsIs passed inside the original component.
  2. Listening to thestore treeChanges so that the original component it wraps can respondstatechange

11. Understanding of higher-order components

A higher-order component is a function that takes a component and returns a new component. HOC is a pure function with no side effects. HOC is common in React third-party libraries, such as Redux’s Connect component.

Functions of higher-order components:

  • Code reuse, logical abstraction, extraction of the underlying preparation (bootstrap) code
  • Rendering hijacked
  • StateAbstractions and changes
  • PropsTo change the

12, which can be used to createReactComponents?

React. CreateClass (), ES6 classes, and stateless functions

13,ReactWhat is the difference between elements and components?

Components are made up of elements. Element data structures are ordinary objects, whereas component data structures are classes or pure functions.

Vue vs. React?

The data flow:

React advocates functional programming, so it advocates pure components, immutable data, one-way data flow,

The idea of VUE is responsive, that is, based on the variable data, Watcher is established for each attribute to monitor. When the attribute changes, the corresponding virtual DOM is updated in a responsive manner.

Monitoring data changes implementation principle:

  • Vuethroughgetter/setterAnd some function hijacking, can know exactly how the data changes, no special optimization can achieve good performance
  • ReactThe default is to compare references, if not optimized (PureComponent/shouldComponentUpdateMay result in a lot of unnecessary VDOM re-rendering.

Component communication differences: JSX and. Vue templates.

  • HoC and Mixins(The way we combine different features in Vue is throughMixin, and inReactWe pass throughHoC(Higher-order components).

Performance optimization

  • React: shouldComponentUpdate
  • Vue: Internal implementationshouldComponentUpdateThe optimization, due to the dependence of the tracking system, exists throughwatcherDetermine if a page needs to be re-rendered (when a page has a lot of data,VueThe performance is poor, resulting in page stuck, so the general data of large projects tend to useReact).

The difference between Vuex and Redux?

In terms of implementation principles, the biggest differences are two:

Redux uses immutable data, whereas Vuex’s data is mutable. Redux replaces the old state with the new state each time, whereas Vuex is a direct modification

Redux uses diff to compare data changes, whereas Vuex uses getter/setter to compare data changes (if you look at Vuex’s source code, you can see that it creates a Vue instance internally to track data changes).

What happens when the browser goes from entering the URL to rendering the page?

Three aspects: Network part: Build a request find a strong cache DNS resolution Establish a TCP connection (three-way handshake) Send an HTTP request (network response after a network request) Parsing HTML to build a DOM Tree parsing CSS to build a CSS Tree, style calculation to generate a Layout Tree (Layout Tree) browser rendering article: Finally, disconnect: TCP wave four times (the browser will send the information of each Layer to the GPU, and the GPU will synthesize the layers and display them on the screen) copy the codeCopy the code

Network security, HTTP protocol

TCP UDP difference

1. 'TCP' provides connection-oriented reliable services to the upper layer, and 'UDP' provides connectionless unreliable services to the upper layer. 2. Although 'UDP' is not as accurate as' TCP 'transmission, it can also be used in many places where real-time requirements are high. High requirements for data accuracy, speed can be relatively slow, you can choose 'TCP' copy codeCopy the code
The difference between UDP TCP
Whether connection There is no connection connection-oriented
reliable Unreliable transmission, not using flow control and congestion control Reliable transmission, using flow control and congestion control
Number of connected objects Supports one-to-one, one-to-many, many-to-one and many-to-many interactive communication It can only be one-to-one communication
transport For a message Word oriented stream
The first overhead The header overhead is small, only 8 bytes Minimum 20 bytes, maximum 60 bytes
Applicable scenario For real-time applications (IP phone calls, video conferencing, live streaming, etc.) Suitable for applications that require reliable transmission, such as file transfer

Difference between Http and Https (high frequency)

1. 'HTTP' urls start with http://, while HTTPS urls start with https:// 2. 'HTTP' is insecure, while HTTPS is secure 3. In the OSI network model, HTTP works at the application layer, while HTTPS's secure transport mechanism works at the transport layer. 5. HTTP cannot be encrypted, while HTTPS encrypts transmitted data. HTTPS requires the SSL certificate copy code issued by the CA organization WosignCopy the code

GET vs. POST (high frequency)

2.GET requests are actively cached by the browser, but POST is not. You need to set the parameters manually. 5.GET parameters are passed through the URL, and POST is placed in the body of the Request. 6. GET is used to query information, and POST is used to submit information for modification. 8.GET generates a TCP packet. POST produces two TCP packet copy codesCopy the code

Understand XSS, CSRF, ddos attacks and how to avoid them

XSS(Cross-site Scripting) is a code injection attack. Attackers inject malicious codes into the target website, and execute these malicious codes when the target logs in. These scripts can read cookies, session tokens, or other sensitive website information, carry out phishing scams on users, and even launch worm attacks.

Cross-site Request Forgery (CSRF) : An attacker induces the victim to access a third-party website and sends cross-site request to the attacked website. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.

XSS Avoid:

  1. urlParameters usingencodeURIComponentWay to escape
  2. Try not to haveInnerHtmlinsertHTMLcontent
  3. Use special symbols, label escapes.

CSRF Avoid:

  1. Adding a Verification Code

  2. Using a token

    • The server generates a token for the user, encrypts it, and sends it to the user
    • Users need to carry this token when submitting requests
    • The server verifies that the token is correct

DDoS, also known as Distributed Denial of Service, overloads resources with a large number of requests, making services unavailable.

DDosHow to avoid:

  1. Limit the frequency of single IP requests.
  2. Protection Settings such as firewalls are disabledICMPPackage etc.
  3. Check that privileged ports are open

HTTP features and status codes

Such as: 200 Response succeeded 301 Permanent Redirection 302 Temporary redirection 304 Resource Cache 403 Server access forbidden 404 Server resources Not found 500 502 Server internal error 504 Server busy 1xx Informational code Accept request processing 2XX Success The request is successfully processed. 3XX Redirection Additional operations are required. Request 4XX Client Error The Server cannot process the request Error (server Error status code) Server processing request Error copy codeCopy the code

HTTP three-way handshake

  • Step 1: The client sends a SYN packet to the server to initiate a handshake. After the packet is sent, the client is in SYN_Send state
  • Step 2: After receiving SYN packets, the server replies SYN and ACK packets to the client
  • Step 3: After receiving the SYN and ACK packets, the client sends an ACK packet to the server. The client changes to Established. After receiving the ACK packet, the server also changes to Established

HTTP four waves

Both parties are in establised state at the beginning, if the client initiates the closing request first, then:

  1. First wave: The client sends a FIN packet with a specified sequence number. The client is in the FIN_WAIT1 state.
  2. Second wave: After receiving the FIN, the server sends an ACK packet and uses the serial number of the client + 1 as the SEQUENCE number of the ACK packet, indicating that the packet has been received. In this case, the server is in CLOSE_WAIT state.
  3. Third wave: If the server also wants to disconnect, the server sends a FIN packet with a specified sequence number as the first wave from the client. The server is in the LAST_ACK state.
  4. Fourth wave: After receiving the FIN, the client also sends an ACK packet and uses the serial number of the server + 1 as the sequence number of its OWN ACK packet. In this case, the client is in TIME_WAIT state. The server enters the CLOSED state after the server receives its ACK packet
  5. After receiving the ACK packet, the server closes the connection and is in the CLOSED state.

Http1.0, HTTP1.1, http2.0

  1. 1 Compared to 1.0, 1.1 can transfer multiple files at once
  2. Http1.x parsing based on text, http2.0 adopts binary format, new features multiplexing, header compression, server push (static HTML resources)

How does HTTP implement caching

  1. Strong Cache ==>Expires/cache-Control (no-cache)(high priority) Negotiated Cache ==> last-Modified /Etag(high priority)Etag is suitable for small files that change frequently Last-mo______ for large documents that don’t change very often
  2. Both the strong cache and negotiated cache policies use the local cache copy directly in case of a cache hit, except that the negotiated cache sends a request to the server once. Both send requests to the server to retrieve resources when the cache misses. In the actual caching mechanism, the strong caching policy and the negotiated caching policy are used together. The browser first determines whether the strong cache hit or not based on the requested information, and if so, uses the resource directly. If the negotiation cache is matched, the server does not return resources and the browser uses a copy of local resources. If the negotiation cache is not matched, the browser returns the latest resources to the browser.

The complete process of an HTTP request after entering a URL

Establish TCP connection -> Send request line -> Send request header -> (to the server) Send status line -> Send response header -> Send response data -> Disconnect TCP connection

Front-end performance optimization

Several ways to optimize front-end performance

Browser cache 2. Anti-shake and throttling 3. Lazy resource loading and preloading 4. Three aspects of enabling Nginx gzip compression to illustrate front-end performance optimization 1: 1. Babel-loader uses include and exclude to help avoid unnecessary translation of js files in node_moudules. 'babel-loader? CacheDirectory =true' 2. Files are loaded on demand etc. 3. To do this, add accept-Encoding :gzip 4 to your Request Headers. 5. Browser cache mechanism, which is divided into strong cache and negotiated cache two: SessionStorage, localStorage, and cookies Event broker 2. Event throttling and stabilization 3. Page backflow and redrawing 4. Code optimization and so on copy codeCopy the code

What is the same origin policy

Js scripts in one domain cannot access content in another domain without permission. Generally, the protocol, domain name, and port number are the same to determine cross-domain. The same origin policy is a restriction on JAVASCRIPT scripts, not browsers. Like IMG,script requests do not have cross-domain restrictions.

How do the front and back ends communicate

Ajax: short connection Websocket: long connection, bidirectional. The Form (original) copy codeCopy the code

Several ways to communicate across domains

Solution:

  1. jsonp(use thescriptTags have no cross-domain limitation for vulnerability implementation. Disadvantages: Only supportedGETRequest)
  2. CORS(setAccess-Control-Allow-Origin: Specifies the domain name of the accessible resource.
  3. postMessage(message, targetOrigin, [transfer]) (HTML5New API for multi-window messaging, page embedded IFrame messaging), throughonmessageListen for incoming data
  4. WebsocketHTML5 is a persistent protocol, it realizes the browser and server full duplex communication, but also a cross-domain solution.
  5. NodeMiddleware proxy
  6. NginxThe reverse proxy
  7. All kinds of nestediframeIs not commonly used.
  8. The most appropriate cross-domain solutions for daily work are CORS and Nginx reverse proxies

Can you talk a little bit about browser local storage? What are the pros and cons?

The localStorage of a browser is divided into cookies, WebStorage, and IndexDB. WebStorage can be divided into localStorage and sessionStorage.

Common: both are saved in the browser and are of the same origin

Difference:

  1. cookieData is always homologoushttpCarried in the request (even if not required), i.ecookieBack and forth between the browser and the server.cookieData and paths (path) can be limitedcookieIt belongs to only one pathsessionStorageandlocalStorageData is not automatically sent to the server, only stored locally.
  2. There are also different storage size limits,
  • cookieData cannot exceed 4K,SessionStorage and localStorageUp to 5M
  • sessionStorage: valid only before the current browser window closes.
  • localStorage: always valid, always saved when a window or browser is closed, locally stored and therefore used as persistent data;
  • cookie: Only in SettingscookieValid until expiration time, even if the window is closed or the browser is closed
  1. Different scope
  • sessionStorage: not shared in different browser Windows, even on the same page;
  • localstorage: is shared in all origin Windows; This means that as long as the browser is not closed, the data still exists
  • cookie: is also shared in all origin Windows. This means that as long as the browser is not closed, the data still exists

Front-end engineering

Webpack configuration, what optimization points webPack 4.0 has

Module. Exports = {entry: {}, the output: {}, plugins: [], the module: [rules: [{}]]} copy codeCopy the code

How does WebPack achieve code separation

  • Entrance to the starting pointUse:entryConfigure manual separation of code.
  • To prevent the repeatUse:CommonsChunkPluginDeweighting and separationchunk.
  • Dynamic import: Separates code by module’s inline function calls.

Common Webpack Loader? How to implement a Webpack Loader(NO)

Loader: is a javascript module exported as a function that processes the file converter according to the rule matching file extension.

14. file-loader: To export files to a folder and reference the output file in code by a relative URL (processing images and fonts)

Url-loader: similar to file-loader except that you can set a threshold. If the threshold is greater than the threshold, the file will be processed by file-loader. If the threshold is smaller than the threshold, the file base64 encoding (processing images and fonts) will be returned.

Image-loader: loads and compresses image files

Babel-loader: Convert ES6 to ES5

Sass-loader: Converts SCSS/SASS code to CSS

Css-loader: loads the CSS and supports features such as modularization, compression, and file import

Style-loader: Inserts CSS code into JavaScript and loads CSS via DOM manipulation

Postcss-loader: extends the CSS syntax to use the next generation CSS. It can be used with the autoprefixer plug-in to automatically complement the CSS3 prefix eslint-loader: checks JavaScript code through esLint

Common Webpack plugins? How to Implement a Webpack Plugin(NO)

Plugin: Plugin is essentially a plug-in, based on the event flow framework Tapable, plug-in can extend the function of Webpack, in the life cycle of Webpack running will broadcast many events, Plugin can listen to these events. Change the output through the API provided by Webpack when appropriate.

Html-webpack-plugin: Simplifies HTML file creation (dependent on html-loader)

Uglifyjs-webpack-plugin: Compress JS files

Clean-webpack-plugin: directory cleanup

Mini-css-extract-plugin: Separate style files, extract CSS as separate files, support on-demand loading (alternative to extract-text-webpack-plugin)

Loader vs. Plugin?

  • Loadermodule.rules , as the parsing rule of the module, type array. Each of these terms is an ObjectAnd the inside containsTest (type file), Loader, options(parameter).
  • Plugin plugins, type array, each item is onePluginThe arguments are passed in through the constructor.

Front-end modular, CMD, AMD, CommonJS

CommonJS

CommonJS is a specification for server-side modules popularized by Node and written in webPack

CommonJs specification:

CommonJS module specification is divided into three parts: module definition, module identification and module reference.

  • Module definition:moduleObject: In each module,moduleObject represents the module itself.exportProperties:moduleObject that provides an interface externally. The best way to output module variables is to usemodule.exportsObject. A single file is a module. Each module is a separate scope, that is, variables defined inside the module cannot be read by other modules unless defined asglobalObject properties.
  • Module identifier: Passed torequireThe argument to the method must be a string with a small hump name or with a.,.. , relative path at the beginning, or absolute path.
  • Module reference: used to load modulesrequire(synchronous load), this method reads a file and executes, returning the internal filemodule.exportsObject.

Advantage:

On the back end, the specification of JavaScript is far behind and has many defects, which makes it difficult to develop large applications using JavaScript. For example: no module system, few standard libraries, no standard interface, lack of package management system, list content

  1. The CommonJS module specification does a good job of solving the problem of variable contamination. Each module has its own space and does not interfere with each other. Namespaces are not so good by comparison.
  2. The CommonJS specification is very simple to define modules and very concise interfaces.
  3. The CommonJS module specification supports import and export functions to smoothly connect modules and achieve dependencies on each other
  4. The CommonJS specification is proposed to compensate for the lack of a standard for JavaScript, which has reached the basic capability of developing large applications like Python, Ruby and Java, rather than remaining in the stage of developing small scripts on the browser side

Disadvantages:

There is no parallel loading mechanism

Since CommonJS loads modules synchronously, this is bad for the server because all modules are stored on the local hard disk. The wait module time is the time the hard disk reads the file. It is very small. However, for the browser, it needs to load modules from the server, related to network speed, agents and other reasons, once the wait time is too long, the browser is in a state of “suspended animation”.

So the browser side wasn’t a good fit for common.js, and there was another specification, AMD

AMD

AMD is an asynchronous module definition specification running in the browser environment. It is the standardized output of RequireJS module definition in the promotion process.

AMD specification

AMD advocates dependency preloading, declaring the module it depends on when defining a module

advantages

The user experience is good because there is no latency and the dependency modules are executed ahead of time.

CMD

CMD is a generic module definition specification; It is the normalized output of the module definition during SeaJs promotion

CMD specification

CMD advocates proximity, requiring only when a module is needed

advantages

Performance is good because it is executed only when the user needs it.

Interview handwritten code series

If the throttle

Function stabilization focuses on firing continuously for a certain period of time, executing only once last, while function throttling focuses on executing only once in a period of time.

Image stabilization

// Definition: the function can only execute once within n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time is recalculated. // The search box searches for input. The user only needs to input the last time before sending the request // mobile phone number, email verification input detection onchange oninput event // window size Resize. Just after the window adjustment is complete, calculate the window size. Prevent repeated rendering. const debounce = (fn, wait, immediate) => { let timer = null; return function (... args) { if (timer) clearTimeout(timer); if (immediate && ! timer) { fn.call(this, args); } timer = setTimeout(() => { fn.call(this, args); }, wait); }; }; Const betterFn = debounce(() => console.log("fn defrag executed "), 1000, true); document.addEventListener("scroll", betterFn); Copy the codeCopy the code

The throttle

// Definition: If an event is continuously triggered, the interval is guaranteed to trigger an event. //1. Lazy load, scroll load, load more, or monitor the scroll bar position; //2. Baidu search box, search association function; //3. Prevent high-frequency click submission, prevent form repeated submission; function throttle(fn,wait){ let pre = 0; return function(... args){ let now = Date.now(); if( now - pre >= wait){ fn.apply(this,args); pre = now; } } } function handle(){ console.log(Math.random()); } window.addEventListener("mousemove",throttle(handle,1000)); Copy the codeCopy the code

Object depth copy

Object. Assign (target,source) 2. es6 Object extension operator. Function deepClone(obj) {if (! obj || typeof obj ! == "object") return; let newObj = Array.isArray(obj) ? [] : {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { newObj[key] = typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key]; } } return newObj; } Duplicate codeCopy the code

Array decrement, array object decrement

// array const arr = [2,7,5,7,2,8,9]; console.log([...new Set(arr)]); / /,7,5,8,9 [2]; / / object is const list = [{age: 18, name: 'Joe'}, {age: 18, name: 'bill'}, {age: 18, name: 'Cathy'}] let the hash = {}; const newArr = arr.reduce((item, next) => { hash[next.age] ? '' : hash[next.age] = true && item.push(next); return item; } []); console.log(list); Copy the codeCopy the code

Array flattening

function flatten(arr) { return arr.reduce((result, item) => { return result.concat(Array.isArray(item) ? flatten(item) : item); } []); } Duplicate codeCopy the code

Professional skills planning, personnel interview

  • What are you going to do in the future? Master/master
  • Personal views on career planning
  • The embodiment of their own value

Leaving reason

  • Personal career planning reasons
  • The company for

other

  1. What is your career plan for the next one to three years?
  2. How do you learn and pay attention to new technology?
  3. What have you learned or summarized from your work in recent years?
  4. What do you think are your strengths and weaknesses in your job?
  5. What are your advantages when you come to our company?
  6. Are there any open source projects?
  7. Have you written NPM packages? Have you written webpack plug-ins?
  8. What framework or library source have you seen? What have you learned?

supplement

In the ES6 symble

It functions like a unique ID. Each Symbol instance is unique. Keys () or for… In, which is not included in the property names of the object itself. So, using this feature, we can use Symbol to define some properties that do not require external manipulation and access. / / the use of Object API Object. GetOwnPropertySymbols (obj) / / [Symbol (name)]

// use the new reflect. ownKeys(obj) // [Symbol(name), ‘age’, ‘title’]

Set and Map in ES6

  • MapObject holds key-value pairs. Any value (object or raw value) can be a key or a value. The constructor Map can take an array as an argument.
  • SetObjects allow you to store any type of value, whether primitive or object reference. It is similar to an array, but the values of the members are unique and there are no duplicate values.

The key of vue

  1. keyThe main function of virtual update is for efficientDOMThe principle isvueinpatchProcess throughkeyCan accurately determine whether two nodes are the same,

In this way, frequent updates of different elements are avoided, making the whole patch process more efficient, reducing DOM operations and improving performance. 3. Vue also uses the key attribute when transitioning between elements with the same tag name, so that VUE can distinguish between them. Otherwise, VUE will only replace its internal attributes without triggering transitions.

The difference between normal functions and arrow functions

  1. Arrow functions are anonymous and cannot be used as constructors. New cannot be used
  2. Arrow functions are not boundargumentsReplace withrestParameters… To solve
  3. Arrow functions are not boundthis, captures its context’s this value as its own this value
  4. The arrow function goes throughCall () or apply ()Method calls a function with only one argument. This is not affected.
  5. Arrow functions have no stereotype attributes
  6. The arrow function cannot be treated asGeneratorFunction, cannot be usedyieldThe keyword

Conclusion:

  • Arrow functionthis Always pointing to its contextthisNo method can change its direction, such ascall() , bind() , apply()
  • The this of an ordinary function refers to the object on which it was called

Kerrization of JS functions

  1. Parameters of reuse
  2. Confirmation in advance
  3. Delay to run
Function add(x, x) Function curryingAdd(x) {return function (y) {return x + y}} add(1, 2) // 3 curryingAdd(1)(2) // 3 Copy codeCopy the code

Implement inheritance dictation

Prootype = new; prooType = new; protoclass constructor= new Call (this) is implemented in subclasses

mapState, mapGetters, mapActions, mapMutations

When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState auxiliary function to help us generate computational attributes. MapMutations actually plays a similar role to mapState, mapping the methods in the component into the store.mit call

A formula for calculating the difficulty of a function

The figure above can be roughly divided into two categories, polynomial magnitude and non-polynomial magnitude. There are only two non-polynomial magnitude-o (2n) and O(n!). The corresponding growth rates are shown below

Vue source code understanding

xxxxx…

Osi7 layer model, TCP5 layer model

Osi7 layer model: physical layer – Data link layer – Transport layer – Network layer – application layer – Session layer – presentation layer

Tcp5 layer model: physical layer – data link layer – transmission layer – network layer – application layer

Write in the last

I’m girl A. I’m very happy to meet you.

  • If there are any errors, please correct them in the comments section. If this article helped you, please like 👍 and follow 😊
  • This article was first published in nuggets. Reprint is prohibited without permission 💌

Interview Mind Map

The article classification

Links: juejin. Cn/post / 698942…