Basically, I can take all the basic questions for the front-end interview

JS based

object.prototype.tostring.call instanceof Array.isArray typeof

1 May be modified prototype chain resulting in errors

The second is to judge whether there is a prototype on the prototype chain. The disadvantage is that the object can only be judged to be modified by the prototype chain, leading to errors

3 is the best method, but there may be incompatibilities

4 Only basic types can be determined

call apply bind

Commonality: Change the this direction

The difference: Bind does not execute immediately, call Apply does; Call takes parameters and apply takes arrays

let const var

Let const does not promote. It cannot be repeated. It is locked. Unlike let, const references to const definitions cannot be modified

defer async

Both load asynchronously, the former when the browser renders and the latter when it finishes loading

Arrow functions and ordinary functions

The rest of the arguments in a function are true arrays. Arguments in a normal function are class arrays and need to be converted to array. from

The former has no prototype, so no context, can’t be used as a constructor, no this, or this points to a parent, no arguments

Function declarations function expressions

The former will create a variable with the same name as the function, pointing to the function, will be created before the code executes, and will always take up memory, so there is variable promotion

The latter creates an anonymous function, and the variable pointing to the function is defined after execution, without promotion

sayHi("John"); // Hello, John

function sayHi(name) {
  alert( `Hello, ${name}` );
}

sayHi("John"); // error!

let sayHi = function(name) {  // (*) no magic any more
  alert( `Hello, ${name}` );
};
Copy the code

Instanceof principle

Determine if the prototype is on the prototype chain

fetch axios

Fetch does not receive a reject error code but a resolve

Axios is also a wrapped XhmHttprequest, if not then go to the Node HTTP module

Var XHR = new XHMHttpRequest(); xhr.open('GET', url); xhr.responseType = 'json'; xhr.onload = function(){}; xhr.onerror = function(){}; xhr.send(); Fetch (url). Then (function(response){return response.json(); }).then(function(jsonData){}).catch(function(){ });Copy the code

webworker

Js is single threaded. With Webworker, you can run a single thread outside the main thread to perform tasks. Messages can be sent to each other through PostMessage

Prototype chain inheritance

Prototype inheritance

function Father() { this.text = '1'; } Father.prototype.someFn = function() { console.log(1); } Father.prototype.someValue = '2'; function Son(){ this.text1 = 'text1'; } // Son.prototype = new Father();Copy the code

Simple and easy to operate, the disadvantage is that it can not be passed to the parent class is not flexible; Parent class attributes are shared by all instances, and subclass changes affect other subclasses

Constructor inheritance

function SuperType(name){ this.name = name; } function SubType() {// SuperType. Call (this, "Nicholas"); // Instance attribute this.age = 29; } let instance = new SubType();Copy the code

Can solve the above problem, but can only inherit the attributes of the parent class, can not inherit the method on the parent class prototype; The function needs to be executed each time it is instantiated and cannot be reused

Combination of inheritance

function Parent(name) { this.name = name this.colors = ["red", "blue", "yellow"] } Parent.prototype.sayName = function () { console.log(this.name); } function Child(name, age) {Parent. Call (this, name) this.age = age; Prototype = new Parent(); Child.prototype.sayAge = function () { console.log(this.age); } let child1 = new Child("yhd", 19); child1.colors.push("pink"); console.log(child1.colors); // ["red", "blue", "yellow", "pink"] child1.sayAge(); // 19 child1.sayName(); // "yhd" let child2 = new Child("wxb", 30); console.log(child2.colors); // ["red", "blue", "yellow"] child2.sayAge(); // 30 child2.sayName(); // "wxb"Copy the code

Fixed the above problem, also because the parent class is executed twice performance poor;

Primary inheritance

function (obj) {
    function A(){}
    A.prototype = obj
    return new A()
}
Copy the code

Good compatibility, like the above one, share inherited data, easy to be affected by modification, cannot pass parameters

Parasitic inheritance

function createAnother(original){ let clone = object(original); SayHi = function() {// Somehow enhance this object console.log("hi"); }; return clone; // Return this object}Copy the code

Disadvantages as

Parasitic combinatorial inheritance

function Father(... Arr) {this.some = 'parent '; this.params = arr; } Father.prototype.someFn = function() { console.log(1); } Father.prototype.someValue = '2'; function Son() { Father.call(this, 'xxxx'); this.text = '2222'; } function inhertPro(son, father){var fatherPrototype = object.create (father. Prototype); // Set son.prototype to Father. Prototype = fatherPrototype; Constructor returns a reference to the Object constructor that creates the instance Object. Here / / keep the constructor to the consistency of the son. The prototype. The constructor = son; } inhertPro(Son, Father); var sonInstance = new Son();Copy the code

Depth Which scenes to copy

Json will be lost function date regex will be converted to string undefined symbol will be lost

object.js

Same as ===, but solves the -0 === +0 true NaN === NaN false problem

react

Principle of diff

The three principles

  • Dom nodes have few operations across hierarchies, only create and delete operations
  • ShouldComponentUpdate is used to control the diff between components. ShouldComponentUpdate is used to control diff between components
  • Compared with the previous method of deleting and creating comparison, the element node is newly added to optimize the identification by key, so as to achieve the movement operation

Why hook

There were a number of issues to be resolved in previous releases

  • It is difficult to reuse the state logic between components. The commonly used solution of higher-order components will bring new problems. Firstly, the code structure needs to be reconstructed, and secondly, it will bring nested hell
  • The life cycle often contains multiple logic and is prone to error, which is also the reason why many people choose to use state management. Hook can be separated
  • The class class is hard to understand and very different from functional components

fiber

React refactoring of the core algorithm

Before 16, the whole update process was synchronous, diff the entire virtual DOM tree from the top down to the web, the whole process can not be interrupted, if the layer is deep, may cause page blocking.

After 2016, Fiber was introduced, which is a work unit bearing various node information as well as an object. Different from before 2016, it solved the pain point. After each fiber is executed, it will check whether there is a task with higher priority, and if there is, the current task will be interrupted. The React team implemented a feature similar to RequesTidlecallBack, which was used without the native API due to its frame limitations.

The purpose of this API is to perform low-priority tasks when the browser is idle

Unsafe Life cycle

  • Componentwillmount the first rendering may be interrupted, so the unmount cycle may not necessarily be executed, causing in-memory rendering
  • Componentwillreceiveprops modify the parent component values in this cycle, may lead to repeated death cycle
  • Componentwillupdate because there’s going to be some time between this and didMount, if you pull up the browser in that time it’s going to cause data errors on the page

New period getSnapshotBeforeUpdate getDerivedStateFromProps

The principle of

  1. In the initialization phase, the mountWorkInProgressHook function will be called every time a hook is used to generate a hook object
  2. The basic structure of a hook object
MemoizedState :null, baseState:null, baseQueue:null, queue: null, next: Null, // point to next hook}Copy the code
  1. After component initialization is complete, a linked list is formed, which is eventually bound to workInProgress’s memoizedState. The hook state is also bound to this property.

The Effect side effect hook, however, is bound to the Update uE of workInProgress and fires sequentially after the commit phase. Get using depth traversal

  1. The updateWorkInProgressHook function is executed during the update

usestate

Call the mountState function at initialization, assign initState to memoizedState and baseState, and Queue holds the events responsible for updating

When updating, get the new hook, merge the queue, update the value, and return the new memoizedState

useeffect

The mountEffect function is called during initialization, the information is stored in memoizedState after the hook is created, and the pushEffect function is also called to put effect into updateQueue of workInProgress

When updating, determine whether dePS has changed or not, if not, execute pushEffect directly, if not, update effect and assign a value to memoizedState

usememo

When initializing, the function for the first argument is executed to generate the value to cache, which is then recorded with dePS and assigned to memoizedState

When updating, determine whether dePS has changed or not, return the cached value directly if there is no update, and regenerate and assign memoizedState if there is an update

function mountMemo(nextCreate,deps){
  const hook = mountWorkInProgressHook();
  const nextDeps = deps === undefined ? null : deps;
  const nextValue = nextCreate();
  hook.memoizedState = [nextValue, nextDeps];
  return nextValue;
}
Copy the code

useRef

When initializing, create a Ref object, save initValue with the object’s current property, and finally write memoizedState

There are no changes when it comes to updating, returning directly to the previous Hook. memoizedState

function mountRef(initialValue) {
  const hook = mountWorkInProgressHook();
  const ref = {current: initialValue};
  hook.memoizedState = ref;
  return ref;
}
Copy the code

Setstate Synchronous or asynchronous

React has a queue mechanism, so it looks asynchronous. The React event sets isbatchUpdate to true to indicate that there is a queue, and then to false when it finishes

In native events and setTimeout, react is not used, so it is synchronized

Why can’t you use hooks inside loops

The principle of hook

Synthetic events

After 17, React reconfigured the composite event mechanism so that the event was tied to the document and is now the root node for every application (i.e., the node that calls reactdom.render)

webpack

Webpack build process

  1. Initialize parameters, read merge parameters from configuration files and shell statements
  2. Load the various plug-ins from the parameters obtained in the first step
  3. Determine the entry, through the entry file, find all the loader that depends on the file to call the configuration for compilation
  4. After compilation, the direct dependencies of each module are obtained and assembled into chunk code blocks containing multiple modules
  5. Writes the output file contents to the file system

loader plugin

Loader is essentially a plug-in that transforms content and preprocesses resources so that WebPack can read them.

Plugin is a plug-in that extends webPack functionality, usually by listening for Webpack events and changing the output as needed

NPM installation principle

  • After NPM install is executed, the dependency tree is recursively retrieved based on package.json
  • Check to see if there is a cache locally, and if not, get the download address remotely from Registry
  • Download package cache. NPM folder, win system cache app-data npm-cache
  • Unpack the downloaded package and write to Node-modules

For duplicate packages, a higher version is saved if they are compatible, and two packages are saved if they are incompatible

COMMONJS

All code runs in the module scope, does not pollute the global, the first load will be cached, subsequent loads will only return the cache results, need to clear the cache before executing again. The output is a copy of the value

It is mainly used in the Node server to load modules synchronously, because the server module files are stored on disk, which is very fast to read. Not applicable to the browser side, because limited by network reasons, more suitable for asynchronous loading

es6 module

  • Commonjs is run time loading, esM is compile time output interface
  • Commonjs loads the entire module, esM loads the individual interfaces within it
  • Commonjs prints a copy of a value, esM prints a reference to a value, and changes within a module can affect the revision of external references
  • A copy of the comonjs value, es6 being a reference to the value

AMD&&requirejs

Asynchronous loading mechanism, for the dependent module, it advocates the dependency before, known in advance, that is to say, the dependency module passed in the define method will be downloaded and executed at the beginning

CMD

It relies on proximity, lazy loading, and is only executed when require is required

Commonjs ESM distinction, circular reference

Esm is a reference to an address

Commonjs will only return what is currently executed, as follows

The module. The export and export

They’re the same thing. The latter is shorthand. The difference is

Export. A = 1 // Normal export = a // cannot be written this way, because it will cause export to point to another reference addressCopy the code

Webpack hot loading principle

Webpack detects the file change, recompiles and stores it in the cache, notifys DevServer, devServer sends the new hash to hMRPlugin, generates a hot-update.json request server through the long link, and retrieves the corresponding JS file from the memory. Then insert it into the document and execute it;

network

Http1 http1.1 HTTP2 Hypertext Transfer protocol was available in 2015

  1. Http1 Every request requires a TCO link

  2. HTTP uses Keepalive to support the transmission of multiple in-domain requests using the same TCP

  3. http2

    • Multiplexing allows a single HTTP to initiate multiple requests simultaneously and frames all transmitted information in binary encoding. Reduce the server connection pressure, less memory footprint, improve the transmission speed

    • Request headers and rows are compressed

    • Support server push

Network security

  1. XSS cross-site scripting attacks

    • Reflective XSS attacker induces the user to access a URL with malicious code, the server receives the data and processes it, and then sends the data with malicious code to the browser, which parses the data with XSS code and executes it as a script, finally completing the XSS attack.
    • Dom XSS mainly shows that the PAGE DOM node is modified, which is a front-end vulnerability
    • Stored XSS persistence stores malicious scripts on the server

    Use coded escape processing

  2. CSRF forges requests across sites

An attack that hijacks a trusted user to send an unexpected request to the server.

Check refer Token authentication

Httponly If this parameter is set, the JS script cannot channel cookie information

OSI seven layer model

TCP UDP

Three-way handshake

  1. The client sends the ayN connection synchronization sequence number to the server and enters the wait state
  2. The server receives the SYN synchronization sequence number and sends it to the client packaged with the ACK confirmation character
  3. The client receives the acknowledgement and sends it to the server
  4. The server sends the data to the client

Four times to wave

  1. End identifier of the FIN returned by the active party
  2. The passive receives the FIN id and returns an ACK packet with the id +1
  3. The passive sends the FIN identifier
  4. The active party receives a FIN and sends back +1

302 304 In-depth principles

301 Permanent redirection 302 Temporary redirection 2 3 7 same, but 2 is http1 standard 304 uses client caching

Strong cache Weak cache

In HTTP1, Expires is used, but because it’s an absolute time, changing the time zone can be problematic, so 1.1 introduced cache-control

Response return header containing cache-conctrol, max-age public private IMmutable; If not, it is read directly from memory; This involves refreshing the browser, which does not change if immutable is specified

The negotiated cache uses an etag similar to hash last-modify to determine the last modification time. The two fields are added to the cache when accessing the resource (will be renamed, the server determines these to return 200 new resources to replace or 304 directly to use the cache)

Principle of CDN

  1. When a user accesses a domain name, the user initiates domain name resolution to the local LDNS
  2. If the LDNS returns any information, query the information from the authorized DNS.
  3. The authorized DNS returns the alias corresponding to the domain name cname.
  4. Then with DNS scheduling system, according to the user node to return the best IP address;
  5. Users access resources based on IP addresses.
  6. If the edge node returns directly, if not, go to the center node and return again

URL URI URN / uniform resource

  • Uri Uniform resource Identifier
  • The subset above the URL, uniform resource locator, contains the path
  • Urn Specifies the unified identification name

They’re all unique urls

The browser

Page rendering process

  1. DNS resolves domain names to obtain IP addresses
  2. Browser access to server
  3. After three handshakes, the server completes processing and returns the resource
  4. The browser takes the resource and parses it to generate the page
    1. Generate a dom tree
    2. Generate cssom tree
    3. Perform js
    4. Generate the render tree
    5. Generate page layout
    6. Render node style

Repaint reflow

Cascading context

Project optimization

  • Reducing HTTP requests
  • Domain name split, increase browser parallel speed
  • Image merging
  • Gzip compression
  • CDN load dependencies
  • According to the need to load
  • Lazy loading

Memory management

These days we typically use reference tags, which mark variables as references when they enter the context and as dereferences when they exit. Instead of just releasing them, we collect them at the next garbage collection.

In older versions of IE, token counting was used, and the early days were real-time garbage collection, which impacted performance

A memory leak

First of all, understand the definition of a memory leak. It means that variables that are not needed are still occupying the memory and will not be released

  1. It is common for internal variables to be promoted to global variables in non-strict mode, so they are not released
  2. The second is timers, when the timer references external variables, the timer does not end, causing the variable to persist
  3. Then there is the DOM reference. For example, if a variable is defined to execute a node, if a is not null after use, then the node will still exist even after deletion

Thread process

Each ongoing program is a process. There are multiple threads in each process, and each thread is responsible for a separate task. The memory of the process is independent and the threads in the process share the memory

Browser web requests are multithreaded, with concurrency limits, and page rendering is single-threaded

Heap heap stack stack

The stack is automatically allocated, automatically released, for example, js primitives are stored in it, first in, first out

The heap is dynamically allocated, usually requiring manual memory freeing. Common reference objects are stored in the heap, and a pointer is stored in the stack to point to the heap address

Interpretive compiled languages

Compilability is usually compiled and run, whereas interpreted languages are compiled at runtime and are slower, but they can be converted to different mechanical codes by different interpreters, so cross-platform support is better

cross-compilation

Generate code on one platform that can be executed on another

Common design patterns

Publish subscribe versus observer

In the latter, the observed maintains an observer queue and notifies the observers themselves of changes

In the former case, the publisher notifies a third party publisher (like a secretary), and the subscriber entrusts a specific subscriber to handle the notification

Design patterns

  1. Decorator pattern – Wraps existing objects by dynamically adding new functionality without changing their structure
  2. The appearance model
  3. The singleton pattern
  4. The proxy pattern
  5. The factory pattern
  6. Iterative model

Programming paradigm

Functional programming object-oriented programming Instruction programming program programming

Aop is faceted oriented programming

An object-oriented way to dynamically add work to other code

Forward proxy Reverse proxy

Both are proxies. The only difference is that one is implemented on the client side and the other on the server side. The former does not know the server address, and the latter does not know the true identity of the requester

service worker

Based on Web worker, it is independent from the main thread and in the middle of the server and browser. It can intercept network requests, cache files, act as a proxy server, access databases and support push

function object_is(a, b) { if (a === b) { return a ! == 0 || 1 / a === 1 / b; } else { return x ! == x && y ! == y; }}Copy the code

event loop

Figure out how it works. Figure out the differences between older Versions of Node

Often appears in the pen test execution order

additional

Why not hash routing with history and distinction

Hash # is a parameter that is added to the URL. The modification does not refresh the url or cause the page to refresh, and is listened for via onhashchange

Using the new pushState() and replaceState() methods in the HTML5 History Interface, you can modify a real URL without causing a page refresh. The refresh is a real URL refresh, but the refresh is 404 and requires backend configuration

Hash is a pure front-end implementation, changes do not refresh the address, history is supported by the H5 native API, but requires server configuration redirection, etc., learn the implementation principles and differences

Why not hash

Because all kinds of exceptions can occur in the wechat environment, it will handle your hash.

Hash routing itself is only a temporary solution, not a formal specification, so it is recommended to use history

Be sure to understand the implementation, not just know

The author ali technical surface did not hang, but because resume crazy brush was almost screened, continue to refueling workers

Brush Lee Code to go, the last hope – Hangzhou byte