This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Writing in the front

Interviews, an essential experience for everyone in the workplace, may be a little more frequent for r & D staff (there is no emotional color here). It is said that no unprepared battle, especially for our technical personnel, before the interview must be well prepared to prepare, you, ready?

I’m Han, a front-end engineer who’s constantly learning, constantly writing bugs

Js data types

  • Basic type: Number String Boolean Null Undefined Symbol BigInt

  • Reference type: Object

Data type determination

  • Typeof:The return value isnumber string boolean undefined symbol bigint object function
typeof null    // object 'since JavaScript was born'
typeof NaN     // number
Copy the code
  • Instanceof: Based on the prototype chain judgment, the reference type can be detected.
  • Constructor: unsafe. The reference to constructor can be changed. Null and undefined do not have this method.
  • Object.prototype.toString.call():Can accurately determine the data type, the return value is[Object uppercase data type].

Statement of ascension

  • Function promotions take precedence over variable promotions and are not overridden by variable declarations, but are overridden by variable assignments and replaced by subsequent functions of the same name.
console.log(typeof(foo));   //function
function foo(){}
var foo = 5;
console.log(foo) / / 5
Copy the code

Let and const

  • There is no variable promotion.
  • Temporary dead zone: As long as there is a let command in the block-level scope, variables declared by it are “bound” to the area and are no longer subject to external influence.
  • Repeated declarations are not allowed.
  • Added block-level scope to JS.
  • constIt’s not the value of the variable that’s guaranteed, it’s the value that the variable points toMemory addressThe stored data cannot be changed.
const obj = {}
// Add a prop attribute to obj
obj.prop = 123
console.log(obj.prop) / / 123

// If obj is pointed to another object, an error is reported
obj = {}
Copy the code

A shallow copy of the js object

  • Shallow copy: Copies only references to objects.

Ps: One layer copy only means that when the property value of an object is a reference type, its nested deep layer cannot be copied

Object.assgin({}, targetObj): Only one layer can be copied

. Operator: copy only one layer

Json.parse (json.stringify (obj)): Copy only one layer. Cannot copy when the value is function, undefined, or symbol. Error while copying an object with a circular reference.

Arr.slice (): Copy only one layer

Arr.concat (): Only one layer can be copied

  • Deep copy: a true copy of an object.
function deepClone(obj) {
  if(typeofobj ! = ='object') {return obj
  }
  const 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
}
Copy the code

this

  • This is the environment object of the currently executing code. It always points to an object in non-strict mode and can be any value in strict mode.
  • This points to the global object in the global execution environment.
  • Inside a function, the value of this depends on how the function is called.
  • This cannot be assigned during function execution, and it may have a different value each time the function is called.
  • This always points to the object that last called it.

Changes the operation to which this refers

  • call, apply, bind
  • Arrow functions (arrow functions do not have their own this and inherit this from the previous level of scope)
  • New When a function is used as a constructor, its this is bound to the new object being constructed.

Ps: new has a higher priority than bind

call, bind, apply

  • Call: call immediately, with a single second argument.
  • Apply: call immediately. The second argument is an array.
  • Bind: not called immediately, returns a new function, and permanently binds this. (This means that once this is bound to a bind, this cannot be changed again.)

Handwritten implementation

  • The core idea of the call implementation is that the call will be executed immediately after the call is called. We will take this from the call method as a property of the first parameter (object) of the call method, and then execute the property and pass the following parameters to it, deleting the property.
Function.prototype.call = function (context = window. args) {
  // Declare a unique fnSymbol
  const fnSymbol = Symbol("fn");
  
  context[fnSymbol] = this;
  // Execution methodcontext[fnSymbol](... args);// Delete the fnSymbol attribute
  delete context[fnSymbol];
}
Copy the code
  • Apply implementation idea is similar to call, directly on the code. The only difference is that the second parameter to apply must be an array.
Function.prototype.apply = function (context = window, argsArr) {
  const fnSymbol = Symbol("fn");
  context[fnSymbol] = this; context[fnSymbol](... argsArr);delete context[fnSymbol];
}
Copy the code
  • Core idea: Bind does not execute immediately, but returns a function
Function.prototype.bind = function (context = window. args) {
  const fnSymbol = Symbol("fn");
  context[fnSymbol] = this;
  
  return function (. _args) {
    // Assemble all parametersargs = args.concat(_args); context[fnSymbol](... args);deletecontext[fnSymbol]; }}Copy the code

Arrow function

  • Arrow functions are easier to write;
  • The arrow function does not have its own this, but inherits this from the next level in the scope chain, and is fixed at definition time. ;
  • Call, bind, apply cannot change the arrow function’s this point;
  • Arrow functions cannot yield and cannot be used as generator functions.
  • The arrow function does not have its own arguments. Accessing arguments in the arrow function actually gets the values in the outer local execution environment;
  • Arrow function has no prototype;
  • You cannot use new.

scope

  • Scope is a set of rules that govern how the engine looks for variables by identifier name in the current scope and in nested child scopes.
  • When we access a variable, when the compiler executes the code, it first looks for the identifier in the current scope. If not, it looks in the parent scope. If not, it looks up until it reaches the global scope. A chain formed during this search is called a scope chain.

closure

  • Closure is a phenomenon. Because of the existence of top-level objects in JS, it can be said that whenever a function is created, the closure will be created at the same time as the function is created.
  • Closures allow you to access the scope of an inner function from within its outer function.
  • The essence of closure generation is that there is a reference to the parent scope in the current environment.
  • Closures look like this:1. Return a function; 2. Pass it as a function parameter; 3. Using callbacks in timers, event listeners, Ajax requests, cross-window communications, Web Workers, or any asynchrony is actually using closures; 4. IIFE(execute function expression immediately) creates a closure that stores the global scope window and the scope of the current function, thus allowing global variables.
var a = 1;
function foo(){
  var a = 2;
  function baz(){
    console.log(a);
  }
  bar(baz);
}
function bar(fn){
  // This is the closure
  fn();
}
2 / / output
foo();


/ / timer
setTimeout(function timeHandler(){
  console.log('111'); },100)

// Event listening
$('#app').click(function(){
  console.log('DOM Listener');
})

var a = 2;
(function IIFE(){
  2 / / output
  console.log(a); }) ();Copy the code

Prototype chain

  • Each instance object has a private __proto__ attribute that points to its constructor’s prototype.
  • When an Object is looking for a property, if the Object itself is not found, it will look for its own prototype Object. If the prototype has not been found, it will continue to look for the prototype Object’s prototype until the Object. This upward lookup chain through archetypal links is called the archetypal chain.

The new keyword

New did three things:

  • Creates a new object and returns it;
  • Refers the __proto__ attribute of the new object to the constructor’s prototype object;
  • The code in the constructor (adding properties to the new object) is executed.
// Implement new by hand
function _new(fn, ... arg) {
  // Create a new object that points its prototype object to the constructor's prototype object
  const obj = Object.create(fn.prototype);
  // Point this to the newly created object and to the constructor
  const ret = fn.apply(obj, arg);
  // Return the result of execution if the constructor is of type Object, otherwise return the newly created Object
  return ret instanceof Object ? ret : obj;
}

Copy the code

Interview questions:

function Constructor() {
    this.a = "123";
    // The first case
    return false
    // The second case
    return[] orreturn{} orreturn () = > {}
    // The third caseThere is noreturn
} 
var obj = new Constructor();

Copy the code

An array of class

  • A class array is an object that has a length property. A typical example of this isarguments
  • Class array to array:
Array.from(arguments);

Array.prototype.slice.apply(arguments);

[].slice.apply(arguments);

[...arguments]
/ /... An extension operator that only works on 'iterable' objects that have the value of the 'Symbol(symbol.iterator)' attribute
Copy the code

Js inheritance

Prototype chain inheritance

Its essence is to point the prototype object of one object to the instance object of another object.

  • Advantages: Multiple instances can share properties and methods defined on the stereotype chain.
  • Disadvantages: Each instance’s modification of a property of a reference type is also shared by other instances, which is not desirable.
  • Disadvantages: Subclasses cannot pass arguments to the superclass constructor when instantiating.

See prototype chain inheritance details

Constructor inheritance

The principle is: in the subclass constructor, through the apply or call form, the superclass constructor, to achieve inheritance.

  • Disadvantages: The instance is not an instance of the parent class, only an instance of the child class.
  • Disadvantages: Subclasses cannot inherit methods on the parent class prototype chain.
  • Disadvantages: The parent function is executed each time a subclass instance is generated.

Combination of inheritance

The idea is to use the prototype chain to achieve the inheritance of the prototype properties and methods, and through borrowing the constructor to achieve the inheritance of instance properties.

Constructor and composition inheritance details

Parasitic combinatorial inheritance

  • Implementation idea: Instead of calling the superclass constructor to specify a subtype stereotype, all we need is a copy of the superclass stereotype
  • In essence, you use parasitic inheritance to inherit the prototype of the parent class and then assign the result to the prototype of the child class.

View the parasitic composite inheritance details

The extends inheritance of Class

  • Classes can be inherited through the extends keyword.
  • Subclasses must call the super method within the constructor method, otherwise an error will be reported when creating an instance.

View the extends inheritance of the ES6 Class

Common design patterns

  • The factory pattern
  • Constructor pattern
  • The prototype pattern
  • Constructor + prototype hybrid mode
  • Observer mode
  • Publish subscribe model

Promise

  • Is a constructor that generates an instance of a Promise.
  • Simply put, a Promise is a container that holds the result of an event (usually an asynchronous operation) that will end in the future.
  • The state of promise objects is not affected by the outside world and can only change from pedding to fullied or rejected.
  • Once the state changes, it doesn’t change again, and it can happen any time.
  • Can't cancel promise
  • If the callback function is not set, the errors thrown by the Promise internally are not reflected externally.
  • In the pedding state, it is impossible to know the current stage of progress (just started or about to be completed).

Implementing a Promise version of Ajax?

The realization idea is simple as follows:

  1. The first thing we need to know to make a web request is that it should be _ajax(URL, params), which means it must have the request address and the request parameter (optional)
  2. Since a promise can be chained to a THEN method, the return value of the then method _ajax must be a Promise object

At this point we have the general frame

function _ajax(url, params){
    const promise = new Promise(a);return promise;
}
Copy the code
  1. Next, let’s enrich the contents:
  2. New a promise that takes a function as an argument
  3. This function takes two arguments, resolve and reject, which are two functions provided by the JS engine
function _ajax(url, params){
    function fn(resolve, reject){}const promise = new Promise(fn);
    return promise;
}
Copy the code
  1. I’m going to create an XHR object which is new XMLHttpRequest()
  2. It then binds the onReadyStatechange event to handle changes to XHR’s readyState property
  3. Next,.open() opens the connection and sets the request mode, the request address, and whether the request is asynchronous or synchronous
  4. You can then add the HTTP request header fields using setRequestHeader(k, v)
  5. Then.send(params) sends the request
function _ajax(url, params){
    function fn(resolve, reject){
        const xhr = new XMLHttpRequest();
        const handleChange = function (){
          
        }
        xhr.onreadystatechange = handleChange;
        xhr.responseType = "json";
        xhr.setRequestHeader("Accept".'application/json');
        xhr.open('POST', url);
        xhr.send(params);
    }
    const promise = new Promise(fn);
    return promise;
}
Copy the code
  1. That’s basically done, so let’s refine the event handler onReadyStatechange in detail
  2. ReadyState:
    • 0: Initialization has not started and open has not been called
    • 1: Open is called but send is not called
    • 2: Send is called, but the server does not respond
    • 3: The server is receiving the response, but the reception is not complete. Generally, no processing is performed here
    • 4: At this time, the response from the server has been received and the data can be processed
  3. Status Indicates that the status code is 200
function _ajax(url, params){
  params = JSON.stringify(params);
  function fn(resolve, reject){
    const xhr = new XMLHttpRequest();
    const handleChange = function (){
      if(this.status === 200 && this.readyState === 4){
        resolve(this.response)
      } else {
        reject(new Error(this.statusText))
      }
    }
    xhr.onreadystatechange = handleChange;
    xhr.responseType = "json";
    xhr.setRequestHeader("Accept".'application/json');
    xhr.open('POST', url);
    xhr.send(params);
  }
  const promise = new Promise(fn);

  return promise;
} 
Copy the code
  1. At this point, our Ajax based on promise is complete
  2. Perfect!

Promise.all()

  • Is used tomultiplePromise instance, wrapped asA newExamples of Promise.
  • Receives an array as a parameter.
  • The elements in the parameter array must be Promise instances; if not, they are converted to Promise instances before being processed.
  • Promise.all() may not be an array, but it must have an Iterator interface and return a Promise instance for each member.
// Generate an array of Promise objects
const promises = [2.3.5.7.11.13].map(function (id) {
  return getJSON('/post/' + id + ".json");
});

Promise.all(promises).then(function (posts) {
  // ...
}).catch(function(reason){
  // ...
});
Copy the code
  • Only if promise.all () parameter arrayThis will be fulfilledOr,One of them becomes rejected, the.then callback function after promise.all () is executed.
  • Note that if a Promise instance is used as a parameter, it defines itselfcatchMethod, then once it isrejectedDoes not triggerPromise.all()thecatchMethods.

Realize the Promise. All ()

Core ideas:

  • An array is passed in as an argument. If it is an empty iterable, resolve is simply done
  • If a promise fails, the returned Promise object fails
  • In any case, the result of the completion state of the Promise returned by promise. all is an array
Promise.all = function(promises) {
    return new Promise(resolve, reject) {
        let result = [];
        let index = 0;
        let len = promises.length;
        if(len === 0) {
            return resolve(result)
        }
        for (let i = 0; i < len; i++) {
            Promise.resolve(promises[i]).then((data) = > {
                result[i] = data;
                index++;
                if(index === len) resolve(result) 
            }).catch((err) = > {
                reject(err)
            })
        }
    }
}
Copy the code

async await

  • Async is the syntax sugar for Generator functions, making asynchronous operations easier.
  • The principle of the async function is to package the Generator function and the automatic actuator in one function.
  • Async means that there are asynchronous operations in the function, and await means that the expression immediately following it needs to wait for the result.
  • The async functionThe await command can be followed by values of Promise objects and primitive types(Values, strings, and Booleans, but automatically converted to an immediately resolved Promise object).
  • The async function returns a Promise object
  • The async function can well be thought of as multiple asynchronous operations wrapped into a Promise object, while the await command is the syntactic sugar of the internal then command.
  • The value returned by the return statement inside the async function becomes an argument to the then method callback.
  • Async throws an error internally, causing the returned Promise object to become reject. The thrown error object is received by the catch method callback.
  • The await command followed by a Promise object returns the result of the Promise object's success. If it is not a Promise object, the corresponding value is returned
async function test() {
   // Use try catch to avoid subsequent code failure
   try {
       const res1 = awaitThe ajax request. }catch {
       // The code to execute on an error
   }
   const res2 = awaitThe ajax request. }Copy the code

Async await Execution time

let a = 0
let b = async () => {
    a = a + await 10
    console.log('2', a) / / - > '2' 10
}
b()
a++
console.log('1', a) / / - > '1' 1
Copy the code

In the above code:

  • First of all, function B executes,
  • The variable a is still 0 before the execution of the await, and the expression after the await is first executed (that is, 10). While the await internally implements a generator, which keeps things on the stack, so a = 0 is saved at this point.
  • Then add the following code (a = 0 + 10) to the microtask queue,
  • Then I jump out of async and execute the following synchronization code, where a++ prints 1,
  • Then all the synchronized code is executed, and the code to be executed in the microtask queue is pushed into the execution stack for execution. At this time, the saved value is taken out and used as a = 0 + 10

Here’s a variant:

let a = 0
let b = async() = > {let a1 = await 10
    a = a + a1
    console.log('2', a) / / - > '2' 11
}
b()
a++
console.log('1', a) / / - > '1' 1
Copy the code

Js event loop mechanism

Js is single threaded, its tasks are divided into synchronous tasks and asynchronous tasks.

  • Synchronous task: A task that is queued on the main thread and can be executed only after the previous task has been executed.
  • Asynchronous task: A task that does not enter the main thread but enters the task queue. An asynchronous task enters the main thread only when the task queue informs the main thread that it is ready to execute.
  • Asynchronous tasks in the task queue are executed only after all synchronous tasks on the main thread have been executed.
  • Task queue is divided into macro task queue and micro task queue.
  • Macro tasks include the following: setTimeout setInterval setImmediate(unique to nodes) requestAnimationFrame(unique to browsers) UIrendering(unique to browsers) I/O
  • Microtasks include: process.nextTick, MutationObserver, promise. then catch finally
  • Microtasks are executed before macro tasks.
  • New Promise() is a synchronous task that executes immediately.
function fn(){
    console.log(1);
    
    setTimeout(() = > {
        console.log(2);
        Promise.resolve().then(() = > {
            console.log(3);
        });
    },0);
    
    new Promise((resolve, reject) = > {
        console.log(4);
        resolve(5);
    }).then(data= > {
        console.log(data);
    });
    
    setTimeout(() = > {
        console.log(6);
    },0);
    
    console.log(7);
}
fn(); 
 
Log (1), new Promise(), console.log(7)]; Macrotask: [setTimeout1, setTimeout2] Microtask: [Promise2.then] Output: 1, 4, 7 2. After all synchronization tasks are executed, the call stack is cleared. Stack: []; macrotask: [setTimeout1, setTimeout2] microtask: [promise2.then] 3. [Promise2.then]; [Promise2.then]; Macrotask: [setTimeout1, setTimeout2] MicroTask: [] 5 4. At this point, the microtask queue is empty, so the macro task is executed, and setTimeout1 in the macro task queue is pushed onto the execution stack. Stack: [setTimeout1]; Macrotask: [setTimeout2] microtask: [] output 2, when performing setTimeout1 and created a task, the stack in the microtask: [] macrotask: [setTimeout2] microtask: [promise1.then] 5. [promise1.then] macrotask: [setTimeout2] microtask: [] Output: 3 6. Stack: [setTimeout2] macrotask: [] microtask: [] Finally, the execution stack and task queue are empty and the code is executed. The final output sequence is: 1 4 7 5 2 3 6 Perfect!! * * /

Copy the code

Shake and throttling

Image stabilization

  • As the name suggests, shockproof is to prevent shaking. So why would it shake? It must be because of the persistent shake, which causes bad effects. For example, if you take a photo with your phone in one hand, your arm will always wobble, which will affect the final result. That’s why we have the anti-shake feature in our apps,To put it in plain English, the function always executes n seconds after the last trigger, no matter how many times it firesAt a time.

Used for: input input box, reduce resource requests; And the resize of window

// fn is the callback function to be executed, delay is the delay time for each delay
function debounce(fn, delay) {
    // Create a timer
    let timer = null;
    
    return function() {
        // Check whether the timer exists before each fn execution. If it exists, clear it so that the timer can be restarted in case of another fn execution
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() = > {
            fn.apply(this, [...argments])
        }, delay)
    }
}
Copy the code

The throttle

  • As the name suggests, it saves traffic. Like water pipes, thick and thin, at the same time the flow of these two pipes is not the same. In our program,When events are continuously raised, the event handler is guaranteed to be called only once in a certain period of time.

Mostly used for: mouse mousedown events; Listen for scroll events, etc.

// Fn is the event handler to execute, interval is the interval threshold
function throttle(fn, interval) {
    // Define the last time the callback event was fired
    let last = 0;
    return function () {
        // Record the current time
        let now = +new Date(a);// Execute an event handler if the difference between the current time and the last time is greater than or equal to the time threshold
        if (now - last >= interval) {
            last = now
            fn.apply(this, [...arguments]); }}}Copy the code

Redraw and backflow

redraw

  • When some elements in the Render tree need to update attributes that only affect the look and style of the element, but not the layout, it is called a redraw. (E.g. Background-color)

Reflux is also called rearrangement

  • When part (or all) of a render tree needs to be rebuilt because of changes in the element’s size, layout, hiding, etc., it is called reflux.
  • Every page needs to be reflow at least once, which is when the page is rendered for the first time. Because you need to build the Render Tree.
  • Backflow is required when page layout and geometry changes.
  • Reflux will inevitably cause redrawing, and redrawing will not necessarily cause reflux.

The property that triggers a redraw

  • color, background-color, visibility, opacity
  • border-style, border-radius
  • The box – shandow, outline, etc

A condition that triggers backflow

  • Backflow is triggered when the DOM element’s geometric properties change. (width, height, padding, margin, border)
  • The movement, deletion, or addition of DOM elements triggers backflow.
  • When reading or writing position attributes such as offset, Scroll, and client, backflow is triggered.
  • Calling window.getComputedStyle also triggers backflow.

How to reduce redrawing and backflow

  • Reduce style operations.
  • Reduce DOM operations
  • Avoid frequent direct access to the computed style and save the information first. (for example, to get the properties of a dom node, see the following code 🙂
for(var i = 0; i<=10; i++){// You should save the dom property information in a variable like this
   var body = document.getElementsByTagName('body') [0]
   var h = body.offsetHeight;
}
Copy the code
  • New Layer: The dom elements that are frequently redrawn and reflow are placed on a separate layer, thus reducing the impact of redrawing and reflow. (For example, virtual DOM)
  • The ABSOLUTE layout of the DOM does not cause a lot of backflow.
  • Don’t nest HTML too deeply, as this will increase the computational cost of the page layout.

The front-end cache

Benefits of caching

  • Reduce redundant data transmission, save broadband traffic.
  • Reduced server burden, greatly improved site performance.
  • This speeds up the client loading of web pages, which is why HTTP caches are part of client caches.

Strong cache

  • Definition: when the requested data exists in the cache library, use the data in the cache library directly. If the requested data does not exist in the cache library, then request the data from the server.
  • Strong caching is primarily through the HTTP request headerCache-ControlandExpireTwo field controls.
  • It’s usually setCache-ControlThe value ofpublic, max-age=xxx: indicates that the resource is accessed again within XXX seconds, the local cache is used, and no request is sent to the server.
  • Expire: indicates the expiration time of data returned by the server. (The cached data is used when the time to request again is less than the return expiration.) This value is generally not processed.

Negotiate the cache

  • The client will first get an id of cached data from the cache library, and then request the server to verify whether the id is valid. If the id is valid, the server will return 304 and use the cached data directly. If not, the server returns the updated data.
  • Last-modified: When the server responds to a request, it tells the browser when the resource was Last Modified.
  • Etag: When the server responds to a request, this field tells the browser the unique identity of the current resource generated by the server (the generation rule is determined by the server).

cookie

  • Data is always carried in the same source HTTP request, that is, back and forth between the browser and the server.
  • Data has the concept of a path, you can limit cookies to a certain path.
  • The storage size is only 4KB
  • Valid only before the set expiration time, regardless of whether the browser is closed or not.
  • Cookie you can set the set-cookie property in the HTTP header:httponlyProperties can preventXSS attacks, which disables js scripts from accessing cookies;sourceProperty tells the browserCookies are sent only when HTTPS is used

sessionStorage

  • Data is stored locally and is not automatically sent to the server.
  • Data is valid only until the current browser window closes and is not persistent.
  • Is shared in all the same origin Windows.
  • There are limits on the size of the data stored. If you save something about 500KB, you will make Resources change card, if you save something about 2M, you will make Resources stuck, you can’t handle it, 5M is the limit of Chrome, and after exceeding it, you will throw an exception.DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'widgetCacheData' exceeded the quota.)

localStorage

  • Data is stored locally and is not automatically sent to the server.
  • Data is always valid, and Windows and browsers are always closed, so data can be persisted.
  • Is shared in all the same origin Windows.
  • There are limits on the size of the data stored. If you save something about 500KB, you will make Resources change card, if you save something about 2M, you will make Resources stuck, you can’t handle it, 5M is the limit of Chrome, and after exceeding it, you will throw an exception.DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'widgetCacheData' exceeded the quota.)

indexedDB

  • Is a low-level API for storing large amounts of structured data (also files/binary large objects (BLOBs)) on the client side.

  • The API uses indexes for high performance searching of data.

  • IndexedDB is a transactional database system similar to an SQL-based RDBMS.

  • IndexedDB is an object-oriented database based on JavaScript. IndexedDB allows you to store and retrieve objects indexed by keys; You can store any object supported by the structured cloning algorithm. All you need to do is specify the database schema, open a connection to the database, and then retrieve and update a series of transactions.

  • Operations performed using IndexedDB are performed asynchronously so as not to block the application.

  • To get access to the database: you need to call the open() method on the indexedDB property of the Window object. This method returns an IDBRequest object; Asynchronous operations communicate with the caller by firing events on the IDBRequest object.

  • The specific use method, can be baidu, here do not do more details.

Fetch, Ajax, Axios

fetch

  • fetch: purported to be an Ajax replacement, based onPromiseDesigned API, is native JS.
  • Fetch can take an optional second argument, an init object that controls different configurations.
  • Fetch does not work out of the box.
  • The FETCH does not support time out control.
  • Fetch differs from jquery.ajax () in three ways:
  1. When an HTTP status code representing an error is received fromfetch()The returnedPromiseWill not be marked asrejectEven if the HTTP status code of the response is 404 or 500. Instead, it marks the Promise state asResolve (but sets the OK property of the return value of resolve to false).The object is rejected only when the network fails or the request is rejected.
  2. Fetch () can accept cross-domain cookies, and you can also use fetch() to set up cross-domain sessions.
  3. Fetch does not send cookies. Unless you use itcredentials 的Initialization options

ajax

  • Ajax is a wrapper around native XHR with support for JSONP.

axios

  • Axios is a PROMISe-based HTTP client for browsers and NodeJS,It’s essentially a wrapper around native XHR, is just an implementation of the Promise, conforming to the latest ES specification.
  • Can be used in nodeJS.
  • Provides an interface for concurrent requests.
  • Support for the Promise API.

HTTP related

What is HTTP?

  • HTTP stands for Hypertext Transfer ProtocolIs a protocol and specification for transferring text, pictures, audio, video, and other hypertext data between two points in the computer world.

Pros and cons of HTTP?

  • Flexible and extensible.
  • Request permission mode
  • Reliable transport
  • Statelessness (both a plus and a minus)
  • Clear transmission
  • Team head block

TCP/IP Protocol (key technology of Internet)

  • TCP: Transmission control protocol; Responsible for communication between applications
  • IP: Internet protocol; Responsible for communication between computers
  • The TCP/IP protocol family is divided into four layers:
  1. The application layer: Specifies the communication protocol for providing application services to users.
  2. The transport layer: Connects to the upper-layer application layer and provides a protocol for data transmission between two computers on a network connection.
  3. The network layer: Specifies the transmission route through which the data reaches the other party’s computer for transmission to the other party (IP protocol, etc.).
  4. The link layer: Deals with the part of the hardware that connects the Network, including the device driver that controls the operating system, the hardware, NIC (Network Interface Card), and the physically visible part such as optical fibers (and all transmission media such as connectors).Hardware categories are within the scope of the link layer.

URI

  • URI: Uniform resource identifier
  • URL: Uniform resource locator
  • URN: Specifies the unified resource name

HTTP Request Mode

  • GET: Usually used to obtain resources
  • POST: Usually used to submit data
  • PUT: Usually used to modify data
  • DELETE: DELETE data (usually not used)
  • HEAD: Obtain the meta information of the resource
  • CONNECT: Establishes a connection channel for the proxy server
  • OPTIONS: Lists the request methods that can be applied to resources for cross-domain requests
  • TRACE: TRACE the transmission path of the request-response

Difference between GET and POST

  • Get passes parameters explicitly on the URL and has a data length limit, while POST passes parameters implicitly and has no data length limit.
  • Data returned by get requests is cached by the browser, while data returned by POST requests is not cached
  • Get queries data, and POST adds, deletes, and changes data
  • Get is less secure than POST and exposes information, but in reality both are less secure because HTTP is used for plaintext transmission and HTTPS is used for security

Partial HTTP status codes

  • 1xx: indicates that the protocol processing is in the intermediate state and further operations are required.
  • 2xx: indicates the success.
  • 3xx: indicates the redirection status. The location of the resource has changed and a new request needs to be made.
  • 4xx: The request packet is incorrect.
  • 5xx: An error occurs on the server.
Status code describe
200 Success indicates that the request from the client was processed correctly on the server.
204 No content indicates that No resources are returned, that is, No body data is contained
206 Partail Content The scope request succeeds
301 Moved, permanently redirected, indicating that the resource has been assigned a new URL
302 Found, temporary redirection, indicating that the resource has been temporarily assigned a new URL
303 See other: indicates that the resource has another URL. Use the GET method to obtain the resource
304 Not modified, this status code is returned when the negotiation cache is hit (independent of redirection)
400 Bad Request: The request packet has a syntax error
401 Unauthorized: requests are sent with HTTP authentication information
403 Forbidden: indicates that the server denies access to the requested resource. You can return the cause description in the entity body
404 Not found: indicates that the requested resource was not found on the server
500 Internal sever Error: indicates that an error occurred while the server was executing the request
501 Not Implemented: Requests from clients are Not supported
502 The server itself is normal, but an error occurred when accessing, the specific error is not known.
503 Service Unavailable Indicates that the server is busy and cannot respond to the Service temporarily

Cross domain

  • Cross-domain is caused by the browser’s same-origin policy.
  • When the protocol, domain name, or port used to request a URL is different from the url of the current page, it is cross-domain.
  • Cross-domain solutions:
  1. CORS is cross-domain resource sharing
  2. JSONP: Use script tag SRC to achieve cross-domain request response, only support get method.
  3. Nginx reverse proxy
  4. Proxy
  5. postMessage
  6. window.name
  7. document.domain

Three handshakes and four waves

  • The first handshake: The client sends a SYN packet to the server.
  • Second handshake: After receiving a SYN packet, the server responds with a SYN+ACK packet.
  • The third handshake: After receiving a SYN+ACK packet, the client responds with an ACK packet.
  • After the server receives an ACK packet, the three-way handshake is established.
  • First wave: The client sends a FIN packet with a serial number specified in the packet. At this point the client is inFIN_WAIT1State.
  • Second wave: After receiving the FIN packet, the server sends an ACK packet. The server uses the client serial number + 1 as the SERIAL number of the ACK packet to indicate that it has received the packet from the client. In this case, the server is in theCLOSE_WAITState.
  • Third wave: After receiving the ACK from the server, the client entersFIN_WAIT2Status. If the server also wants to disconnect, it sends a FIN packet to the client and specifies a serial number. The server is inLAST_ACKIn the state.
  • The fourth wave: After receiving the FIN packet, the client replies with an ACK packet and uses the server serial number + 1 as the serial number of its ACK packet. In this case, the client is in theTIME_WAITState. After receiving the ACK, the server entersCLOSEDThe server has completed closing the connection.

Check out: Follow the animation to learn TCP three handshakes and four waves

https

  • Hypertext Transfer Security Protocol.
  • HTTPS communicates over HTTP, but uses SSL/TLS to encrypt packets. The main purpose of HTTPS development is to provide identity authentication for web servers and protect the privacy and integrity of exchanged data.

What happens between entering the URL and the end of the page rendering?

  • Enter the URL in the browser’s address bar and press Enter.
  • The browser checks whether the current URL is cached and compares whether the cache is valid.
  • DNS resolves the IP address corresponding to the URL.
  • Establish a TCP connection based on IP (three-way handshake);
  • HTTP initiates a request;
  • The server processes the request and the browser accepts the response.
  • Render the page and build the DOM tree;
  • Close the TCP connection (four waves)

What is Babel?

  • Babel is a JS translator that converts ES2015 + code into a backward compatible JS version in both current and older browsers or environments.
  • Transformational grammar;
  • Missing polyfill functionality in the target environment
  • Source code conversion

Js event flow

  • Flow of eventsDescribes the order in which events are received from the page.
  • IE’s event stream is an event bubble stream
  • The event flow of Netscape Communicator is the event capture flow

The event bubbling

  • Events are initially received by the most specific element and then progressively propagated up to less specific nodes

Event capture

  • The idea of event capture is that the less specific nodes should receive events earlier, while the most specific nodes should receive events last.
  • The purpose of event capture is to capture an event before it reaches its intended target.

The DOM event flow

  • The DOM2 event flow consists of three phases:Event capture phase,In the target stage,Event bubble phase

What does Eval do?

  • eval()The function executes the string as if it were JavaScript code.
  • eval()A function is a function property of a global object.
  • A parameter is a string representing a JavaScript expression, statement, or sequence of statements.
  • Return value: Returns the return value of the code in the string. If the return value is null, undefined is returned.
  • ifeval()Is not a string,eval()Returns the parameter intact.
  • You should avoid using eval. It’s unsafe and performance intensive (twice, once parsed into a JS statement and once executed).
  • Var obj =eval(‘(‘+ STR +’)’);

Write a series of

Implement a new

/** we create a new object and return it. We point the __proto__ property of the new object to the constructor. Executes the code in the constructor (adding properties to the new object) */
function _new(fn, ... arg) {
  // Create a new object that points its prototype object to the constructor's prototype object
  const obj = Object.create(fn.prototype);
  // Point this to the newly created object and to the constructor
  const ret = fn.apply(obj, arg);
  // Return the result of execution if the constructor is of type Object, otherwise return the newly created Object
  return ret instanceof Object ? ret : obj;
}

Copy the code

Look at a chestnut:

function Constructor() {
    this.a = "123";
    // The first case
    return false
    // The second case
    return[] orreturn{} orreturn () = > {}
    // The third caseThere is noreturn
} 
var obj = new Constructor();

Copy the code

Event Bus (publish-subscribe pattern)

class EventEmitter {
    constructor() {
        this.cache = {}
    }
    on(name, fn) {
        if (this.cache[name]) {
            this.cache[name].push(fn)
        } else {
            this.cache[name] = [fn]
        }
    }
    off(name, fn) {
        let tasks = this.cache[name]
        if (tasks) {
            const index = tasks.findIndex(f= > f === fn || f.callback === fn)
            if (index >= 0) {
                tasks.splice(index, 1)}}}emit(name, once = false. args) {
        if (this.cache[name]) {
            // Create a copy. If the callback continues to register the same event, it will cause an infinite loop
            let tasks = this.cache[name].slice()
            for (let fn oftasks) { fn(... args) }if (once) {
                delete this.cache[name]
            }
        }
    }
}

/ / test
let eventBus = new EventEmitter()
let fn1 = function(name, age) {
	console.log(`${name} ${age}`)}let fn2 = function(name, age) {
	console.log(`hello, ${name} ${age}`)
}
eventBus.on('aaa', fn1)
eventBus.on('aaa', fn2)
eventBus.emit('aaa'.false.'布兰'.12)
// 'Bran 12'
// 'Hello, Bran 12'

Copy the code

The function is curialized

  • Function currying is going to useA function with multiple argumentsConverted toA series of functions that take one argumentThe technology.

See 🌰 :

function add(a, b, c) {
    return a + b + c
}
add(1.2.3)
let addCurry = curry(add)
addCurry(1) (2) (3)
Copy the code

Implement the Curry function:

function curry(fn) {
    let judge = (. args) = > {
        if (args.length === fn.length) {
            returnfn(... args) }return (. arg) = >judge(... args, ... arg) }return judge
}
Copy the code

Implement instanceof

// The core is looking up the prototype chain
function instanceof(left, right) {
    Return false if it is a primitive type
    if(typeofleft ! = ='object' || left === null) {
        return false
    }
    // Get the prototype object for the left argument
    let proto = Object.getPrototypeOf(left)
    while(true) {
        // Return false if the top of the prototype chain is not found
        if(proto === null) {return false
        }
        if (proto === right.prototype) {
            return true
        }
        / / iteration
        proto = Object.getPrototypeOf(proto)
    }
}
Copy the code

For more details on the handwriting series, please go to:

  • Dead knock 36 JS handwritten problem
  • “Advanced front end interview” javaScript handwriting unbeatable secrets

Do not finish the comprehensive test

[‘1’, ‘2’, ‘3’].map(parseInt)

  • parseInt(string, [radix]): Receives two parameters
    • String (required) : String to be parsed.
    • Radix (optional) : radix of numbers to be parsed, between 2 and 36.
      • If the parameter is omitted or its value is 0, the base 10 is used for parsing;
      • If it starts with ‘0x’ or ‘0x’, it is resolved in base 16;
      • ParseInt () returns NaN if its value is less than 2 or greater than 36.
  • ParseInt () returns NaN when the first non-space character cannot be converted to a number.

If (a == 1 && a == 2

let a = {
    value: 0.valueOf() {
        this.value++;
        return this.value
    }
}
Copy the code

Recursively implement the sum of integers from 1 to n

function count(n) {
    if (n === 1) {
        return 1
    }
    return count(n - 1) + n
}
let sum = count(100);
console.log('and,', sum);
Copy the code

A very comprehensive interview question

function Foo () {
    getName = function () { alert(1)}return this
}
Foo.getName = function () { alert(2) }
  
Foo.prototype.getName = function () { alert(3)}var getName = function () { alert(4)}function getName () { alert(5) }


Foo.getName(); / / 2
getName(); / / 4
Foo().getName(); / / 1
getName(); / / 1
new Foo.getName(); / / 2
new Foo().getName(); / / 3
new new Foo().getName(); / / 3
Copy the code

To know the detailed answer, please move: a basic problem that is ignored by the front end, do not believe that you can several questions

Write in the last

The purpose of this series of articles is to record the front-end knowledge, and will not be too detailed. At the initial stage, it may not be very comprehensive, and the follow-up will be supplemented and improved from time to time. At the same time, you are welcome to comment and add, if there are mistakes, please comment and point out, I will timely correct. Finally, welcome to the triple button.

I’m Han. Pay attention to me not to get lost, study together, progress together.