preface

To highlight

This east east is collected around, and then tidy up their own, if the infringement of the interests of the original author, if caused infringement and other problems, please contact me quickly! Delete it now!! I wish you an early job landing!! Blunt duck!!!!! If there are any mistakes, let me know in the comments section! I go to change!! Come on!

Small dish chicken interview experience juejin.cn/post/684490…

That ans start cough up!! Rush duck!!

Because most of these are also collected from the Internet, if you find any mistakes, please point out in the comment area, I go to correct correction!

1. Simulate the process of new

Implementation steps

  1. Create a new object, obj
  2. By linking to the stereotype (the stereotype of the new object points to the stereotype of the constructor to be inherited), OBj has access to the properties of the constructor stereotype
  3. By binding this to implement inheritance, OBj can access the constructor’s properties
  4. The constructor returns an object if it does, or obj if it does not
function Animals(name, color){
    this.name = name
} 

Animals.prototype.action = function () {
  console.log(this.name, 'walk')
Copy the code

You define a constructor and its prototype method and then you implement a create method to simulate new

function create(constructor, ... args){
    const obj = new Object()
    obj.__proto__ = constructor.prototype
    const res = constructor.apply(obj, args)
    return res instanceof Object ? res : obj
}
Copy the code

Specific usage:

const dog = create(Animals, 'dog'.'red')

// const cat = new Animals('cat', 'yellow')
Copy the code

Changing and inheriting properties by changing an object’s [[Prototype]] property can have a serious impact on performance, and the time spent on performance is not as simple as obj.proto =… It also affects all objects inherited from the [[Prototype]] statement. If you care about performance, you shouldn’t change an object’s [[Prototype]].

So we can change the orientation of the obj prototype in another way, by inheriting it from object.create ()

function create(constructor, ... args) {
  const obj = Object.create(constructor.prototype)
  const res = constructor.apply(obj, args)
  return res instanceof Object ? res : obj
}
Copy the code

2. Function anti-shake and throttling

First, simulate user input

<div>
  <input id="input"></input>
  <div id="text">0</div>
</div>
Copy the code

Then anti-shake and throttling

/ / image stabilization
const debounce = function (fn, delay = 1000) {
  let time = null
  return function (. args) {
    let that = this
    time && clearTimeout(time)
    time = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

/ / throttling
// Time stamp version
function throttle(fn, delay = 500) {
  let last = 0
  return function (. args) {
    let now = new Date().getTime()
    if (now - last > delay) {
      last = now
      fn.apply(this, args)
    }
  }
}}

// Timer version, the first call will be delayed
const throttle = function (fn, delay = 1000) {
  let time = null
  return function (. args) {
    let that = this
    if(! time) { time = setTimeout(function () {
        time = null
        fn.apply(that, args)
      }, delay)
    }
  }
}
Copy the code

I’m gonna call it

const input = document.getElementById('input')
input.oninput = debounce((e) = > {
  document.getElementById('text').innerTexte.target.value
}, 1500)
Copy the code

This way you can achieve function tremble and throttling

There is an easier way to use setTimeout to use the arrow function, so you can use this instead of generating that

const debounce = function (fn, delay = 1000) {
  let time = null
  return function (. args) {
    time && clearTimeout(time)
    time = setTimeout((a)= > {
      fn.apply(this, args)
    }, delay)
  }
}
Copy the code

3. Enter the URL to the presentation process

  1. URL parsing, if there are illegal characters, escape
  2. Determine if the requested resource is in the cache
  3. The DNS
  4. TCP three-way handshake
  5. Send the request, analyze the URL, and set the request header
  6. The server returns the requested file (HTML)
  7. Browser rendering
    • Parsing HTML files to generate dom trees
    • Parse the CSS file to generate the style tree
    • Combine DOM tree and style tree to generate render tree
    • Layout layout
    • Draw pages with GPU pixels

4. Currization of functions

// Implement an add method that meets the following expectations: add(1)(2)(3) = 6; add(1, 2, 3)(4) = 10; add(1)(2)(3)(4)(5) = 15;Copy the code

The main thing is to collect the parameters that are passed in

function curry(){
    const argsList = [...arguments]
    
    const fn = function(){ argsList.push(... arguments)return fn
    }
    
    fn.toString = function(){
        return argsList.reduce((a, b) = > a + b)
    }
    
    return fn
}

console.log(curry(1.2) (3) (4.5.6)) / / 21
Copy the code

And now that we’re done with this problem, we’re free to pass in arguments to sum it up, and then we can turn an ordinary function into a Cremation function

function sum(a, b, c) {
  return a + b + c
}
function curry(fn) {
  const argsList = [...arguments].splice(1)
  return function () {
    const newArgsList = argsList.concat([...arguments])
    if (newArgsList.length < fn.length) {
      If the number of parameters received has not reached the number of parameters of the function, continue to collect parameters
      return curry.apply(this, [fn, ...newArgsList])
    } else {
      return fn.apply(this, newArgsList)
    }
  }
}
const sumAll = curry(sum)
console.log(sumAll(1) (2) (3)) / / 6
console.log(sumAll(1) (2.3)) / / 6
Copy the code

5. Redraw and reflow

1. Redrawn

When the element style changes without affecting the layout, the browser will use redraw to update the element, which is less costly because only the UI level is drawn

2. Return

The browser rerenders the page when the element size, structure, or triggers certain attributes, which is called backflow. In this case, the browser needs to recalculate the page layout, so the loss is high

Generally, there are the following operations:

  • Page first render
  • The browser window size changes
  • Element size, position, and content changes
  • Element font size changed
  • Add or remove visible DOM elements
  • Trigger CSS pseudo-classes, such as:hover
  • Query some properties or call some methods
    • clientWidth, clientHeight, clientTop, clientLeft
    • offsetWidth, offsetHeight, offsetTop, offsetLeft
    • scrollWidth, scrollHeight, scrollTop, scrollLeft
    • getComputedStyle()
    • getBoundingClientRect()
    • scrollTo()

Backflow must trigger redrawing, redrawing does not necessarily trigger backflow, the cost of redrawing is small, the cost of backflow is large

How to avoid redrawing and reflow

CSS:

  • Avoid table layouts
  • Modify the class as far as possible at the end of the DOM tree
  • Avoid using multiple inline styles
  • Apply the animation effect toposition: absolute || fixedon
  • Avoid using CSS expressions (e.gcalc)
  • CSS3 Hardware acceleration (GPU acceleration)

JavaScript:

  • Avoid manipulating styles too often. It is better to change the style property once, or define the style list as class and change the class property once
  • To avoid frequent dom manipulation, create onedocumentFragmentApply all the DOM manipulation to it, and finally add it to the document
  • You can also set the element firstdisplay: noneDisplay it after the operation, because dom manipulation on elements with display none does not cause redraw and reflow
  • Avoid frequently reading properties that cause redraw backflow, and cache them in a variable if they need to be used more than once
  • Use absolute positioning on elements with complex animations to keep them out of the document stream, which would otherwise cause frequent backflow of parent elements and subsequent elements
  • Use cssText to change styles

6. Browser storage

  • cookieUsually used to store user information, login status, etc., can set the expiration time, the upper limit of the volume is 4K
  • localStorageThe storage capacity is unlimited and the upper limit is 4 to 5M
  • sessionStorageIf the browser window is closed, it is deleted. The upper limit is 4 to 5M

7. Network request mode Post and GET

  • getIt is cached by the browser, and the request length is limited. It is recorded in the history. When the browser backs back, it is harmless and sends a TCP packet without the request body
  • postMore secure, more encoding types, can send big data, browser back when the request will be submitted again, usually with the request body, send two TCP packets

When the network is poor, POST sends two TCP request packets for better integrity verification

8. TCP three-way handshake

Why a TCP handshake

An error occurs in case an invalid connection request segment is suddenly sent back to the server

  1. The client sends a SYN request and enters the SYN_send state, waiting for confirmation
  2. The server receives and acknowledges the SYN packet, sends the SYN + ACK packet, and enters the SYN_RECv state
  3. The client receives the SYN + ACK packet and sends the ACK packet. The two parties enter the Established state

9. TCP wave four times

  1. The client sends the FIN to the server to disable data transmission from the client to the server. The client enters the fin_wait state
  2. After receiving the FIN, the server sends an ACK packet to the client. The server enters the close_wait state
  3. The server sends a FIN to the client to disable data transmission from the server to the client. The server enters the last_ACK state
  4. After receiving the FIN, the client enters the time_wait state and sends an ACK to the server. The server enters the Closed state

Why is establishment three handshakes and closure four waves?

The client receives a SYN + ACK packet when establishing a connection. After the server accepts the FIN, the client simply stops sending data, but can still receive data. The server can choose to close the connection immediately, or send more data and then send a FIN packet to close the connection. Therefore, FIN and ACK packets are generally sent separately.

10. Memory leaks

  • Unexpected global variables
  • closure
  • A timer that has not been emptied
  • Undestroyed event listening
  • Dom references

11. Characteristics of class inheritance

class Dog {
  constructor(name) {
    this.name = name; }}class Labrador extends Dog {
  / / 1
  constructor(name, size) {
    this.size = size;
  }
  
  / / 2
  constructor(name, size) {
    this.name = name;
    this.size = size;
  }
  
  / / 3
  constructor(name, size) {
    super(name);
    this.size = size; }};Copy the code

As in the code above, both 1 and 2 raise ReferenceError and raise a ReferenceError because in a subclass, there is no way to access this until super is called

12. Common regular expressions

Regular expression set validates digits: ^[0-9]*$Validates n digits: ^\d{n}$Validates at least n digits: ^\d{n,}$Validates m-n digits: ^\d{m,n}$Validates zero and non-zero digits: ^ (0 | [1-9] [0-9] *) $validation has two decimal places are real Numbers: ^ [0-9] + (. [0-9] {2})? $Verifies positive real numbers with 1-3 decimal places: ^[0-9]+(.[0-9]{1,3})? $validates non-zero positive integers: ^\+? [1-9] [0-9] * $validation nonzero negative integer: ^ \ - [1-9] [0-9] * $validation non-negative integer (positive integer + 0) ^ \ d + $to verify the positive integer (negative integers + 0) ^ ((\ d +) | (0 +)) $validation length is 3 characters: ^.{3}$Verifies A string of 26 letters: ^[A-zA-z]+$Verifies A string of 26 upper-case letters: ^[A-z]+$Verifies A string of 26 lower-case letters: ^[A-z]+$Verifies A string of 26 lower-case letters: ^[A-z]+$Verifies A string of 26 numbers and 26 letters: ^[a-za-z0-9]+$verify user password :^[a-za-z]\w{5,17}$the correct format is as follows: start with A letter and contain only 6 to 18 characters, digits, and underscores (_). Verify that it contains ^%&',; =? $\" and other characters: [^%&',; =? $\ x22] + verify Chinese characters: ^ [\ u4e00 - \ u9fa5] and {0} $verify Email address: ^ \ w + / - +. * @ \ w + \ w +) (\ w + [-]) * \ \ w + ([-] \ w +) * $validation InternetURL: ^http://([\w-]+\.) +[\w-]+(/[\w-./?%&=]*)? $; ^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(? S*)? $verify phone number: ^ (\ d3, 4 \ d3, 4 | \ d {3, 4} -)? \d{7,8}$: -- the correct format is xxxx-xxxxxxx, xxxx-xxxxxxxx, xxx-xxxxxxx, xxx-xxxxxxxx, XXXXXXX, XXXXXXXX. Verify identification number (15 or 18 digit) : ^ \ d {15} | \ d {} $18 validation of 12 months of the year: ^ (0? [1-9] | 1 [2-0]) $correct format for: "01" - "09" and "1" "12" validate a month of 31 days: ^ ((0? [1-9]) | | 2 (1) ([0-9]) | | 31) $30 correct format is: 01, 09 and 1, 31. Integer: ^ -? \d+$non-negative float (float + 0) : ^\d+(\.\d+)? $are floating-point ^ (([0-9] + \. [0-9] * [1-9] [0-9] *) | ([0-9] * [1-9] [0-9] * \ [0-9] +) | ([0-9] * [1-9] [0-9] *)) $is a floating point number (negative floating point number + 0) ^ ((\ d + (. \ \ d +)?) | (0 + (\. 0 +)? Negative float) $^ (- (([0-9] + \. [0-9] * [1-9] [0-9] *) | ([0-9] * [1-9] [0-9] * \ [0-9] +) | ([0-9] * [1-9] [0-9] *))) $floating-point ^ (-? \d+)(\.\d+)? $Copy the code

13. Cross domain

Link, IMG,script tags can cross domains

Cross-domain behavior

  • Same-origin policy restrictions, security considerations (e.g., cookies)
  • Different protocols, IP addresses, and ports are cross-domain behaviors

Common cross domain

  • jsonp
  • cors
  • websocket
  • postMessage + iframe
  • document.domain + iframe
  • window.name + iframe
  • Nginx proxy
  • Iframe is nested across domains

JSONP

const script = document.createElement('script')
script.type = 'text/javascript'

script.src = 'xxx.com/login?user=xxx&password=123&callback=onBack'
document.head.appendChild(script)

function onBack(res) {
    console.log(res)
}
Copy the code

CORS cross-domain

Cross-orgin Resources Share (CORS) allows the browser to send XMLHttpRequest requests to the server to overcome the cross-domain problem. It requires both the browser and the server to support it

  • The browser side automatically adds to the request headerorginField indicating the source of the current request
  • The server needs to set the response headerAccess-Control-Allow-Methods.Access-Control-Allow-Headers.Access-Control-Allow-Origin“, specifying allowed methods, headers, sources, and so on
  • Requests are classified into simple requests and non-simple requests. Non-simple requests are processed firstOPTIONSRequest to determine whether cross-domain is currently allowed

A simple request

The request method is one of three:

  • HEAD
  • POST
  • GET

The Http request header does not exceed the following fields:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-type (limited to three values:application/x-www-form-urlencoded,multipart/form-data,text/plain)

Backend response header information:

  • Access-Control-Allow-Orgin: This field must have its value either when requestedorgin, or * to accept access to any domain name
  • Access-Control-Allow-Credentials: This field is optional and is a Boolean value that indicates whether to allow sendingcookies
  • Access-Control-Expose-Headers: This field is optional if you want the XMLHttpRequest objectgetResponseHeader()Method to get more headers is specified in this field

Non-simple request

Non-simple requests refer to the requests that have special requirements on the server, for example:

  • The request method isPUTandDELETE
  • Content-Typeforapplication/json

Non-simple requests add an HTTP query request before formal communication, called options

  • Access-Control-Request-Methor: This field must be used to indicate which HTTP methods the browser’s CORS request uses, for examplePUT
  • Access-Control-Request-Headers: This field is a comma-separated string that specifies the additional request header information to be sent by a browser CORS request

CORS versus JSONP

  • JSONP can only be usedGETRequests, CORS supports all types of HTTP requests
  • JSONP has the advantage of supporting older browsers and being able to send requests to sites that do not support CORS

14. The cache

In fact, when developers build with Webpack, the suffix has a hash value, which is actually related to caching

Caches can be divided into strong cache and negotiated cache. The strong cache is not a server, and the negotiation cache needs to go through the server. The status code returned by the negotiation cache is 304. Both caches can exist at the same time, and the strong cache has a higher priority than the negotiated cache. When strong caching is performed, if the cache is hit, the data in the database is directly cached without negotiation caching.

Strong cache

Expires (HTTP 1.0) : The Expires value is when the data returned by the server Expires. When the rerequest time is less than the expiration time, the cached data is used directly. However, errors in cache hits may occur due to time errors between the server and client. In addition, most use cache-control instead

Pragma (HTTP 1.0) : A field left over from HTTP 1.0 that forces validation caching when the value is no-cache. Pragma disables caching and takes precedence if an unexpired time is defined for Expires. The server responds by adding Pragma: no-cache, and the browser behaves similar to refresh (F5)

Cache-control (HTTP 1.1) : Has the following properties

  • Private: The client can cache
  • Public: Both client and proxy servers can cache
  • Max-age =t: The cache contents will be invalid in t seconds
  • No-cache: A negotiated cache is required to validate cached data
  • No-store: All content is not cached

No cache does not mean that the cache is not available. No cache means that the cache is available, but the server verifies that the cache is available each time. No-store does not cache content.

Cache-control takes precedence over Expires when a max-age is specified in the response header.

Format of strong cache hits: Gray 200 status code for Firefox, 200(from disk cache) or 200 OK(from memory cache) for Chrome

Negotiate the cache

Negotiation caches require comparison to determine whether caches can be used. The first time the browser requests data, the server responds with the cache id along with the data to the client, which backs it up to the cache. When requested again, the client sends the cached identifier to the server, which determines the representation. If not, the 304 status code is returned. The browser gets the status code and can use the cached data directly.

Last-modified: When the server responds to a request, it tells the browser when the resource was Last Modified. This may result in multiple last-second modifications, or the time difference between the server and the client may result in a cache miss, so eTAG was introduced

If-modified-since: The request header contains this field when the browser requests the server again, followed by the last modification time obtained in the cache. After receiving this request, the server finds if-modified-since, and compares it with the last modification time of the requested resource. If the request is consistent with the last modification time of the requested resource, the server returns a 304 response. The browser only needs to retrieve data from the cache

  • If the resource has been modified, the server transmits the whole data and the server returns 200 OK
  • If it has Not been Modified, the server simply transmits the response header and the server returns 304 Not Modified

If-unmodified-since: Indicates whether the file has not been modified Since a certain point in time. The relative time is used, regardless of the time difference between the client and the server.

  • If it has not been modified, the transfer continues and the server returns 200 OK
  • If the file is modified, no feed is transmitted, and the server returns 412 Preprocessing failed

The difference between these two is that one is modified before downloading, one is not modified before downloading.

If, on the server, a resource is Modified but its actual contents have not changed at all, the last-Modified time does not match and the entire data is returned to the client (even if the client cache contains an identical resource), we need to use HTTP 1.1 Etag to solve this problem

Etag: This field tells the browser the unique identity of the current resource generated by the server when the server responds to a request (the generation rule is determined by the server)

If-match: conditional request that carries the Etag of the resource in the previous request. The server uses this field to determine whether the file has been modified

If-none-match: If the browser requests the server again, the header of the request packet contains this field. The following value is the id obtained from the cache. After the server receives the request packet, if-none-match is compared with the unique representation of the requested resource

  • If no, the resource has been modified, and the status code 200 is returned
  • If yes, the resource has not been modified. The browser responds with the header, and the server returns the status code 304

Etag is more accurate than last-Modified, and belongs to strong authentication. It requires consistent resource byte level and high priority. If the server provides an ETag, a Conditional Request for the ETag must be made first.

However, in practical applications, Etag is seldom used because the calculation of Etag is derived from the algorithm, and the algorithm will occupy the resources of the server calculation. All the resources on the server side are precious

  • When the browser enters the URL and hits press, the browser finds that the file is already in the cache and retrieves the data from the cache instead of continuing the request
  • F5 refresh is when the browser sends a request to the server, carryingIf-Modified-SinceTo see if the file is out of date
  • Ctrl + F5 force refresh, that is, first delete the cache file, and then go to the server to request a complete resource, so the client has completed the force update operation

Caching scenario

Strong and negotiated caching can be used for most scenarios, but in some special cases, you may need to choose a special caching strategy

  • For some resources that do not need caching, you can use itCache=Control: no-storeTo indicate that the resource does not need caching
  • This parameter can be used for resources that change frequentlyCache-Control: no-cacheAnd cooperate withEtagIf yes, the resource is cached, but a request is sent each time asking whether the resource is updated
  • For code files, it is usually usedCache-Control: max-age=31536000It is used in conjunction with the policy cache, and the file is fingerprinted. Once the file name changes, new files will be downloaded immediately

15. Write call, apply, bind by hand

Function.prototype.myCall = function (obj = window) {
  obj.fn = this
  const args = [...arguments].splice(1)
  constresult = obj.fn(... args)delete obj.fn
  return result
}

Function.prototype.myApply = function (obj = window) {
  obj.fn = this
  const args = arguments[1]
  letresult = args ? obj.fn(... args) : obj.fn()delete obj.fn
  return result
}

Function.prototype.myBind = function (obj = window) {
  const that = this
  const args = [...arguments].splice(1)
  return function () {
    return that.apply(obj, [...args, ...arguments])
  }
}

// Then use it
function log() {
  console.log(this)
  console.log(this.value)
  console.log(arguments)}const obj = {
  value: 123
}

log.myCall(obj, 1.2.3)
log.myApply(obj, [1.2.3])
log.myApply(obj)
log.myBind(obj)()
log.myBind(obj)(1.2.3)
log.myBind(obj, 4.5.6) (1.2.3)
Copy the code

16. The difference between pseudo-classes and pseudo-elements

Pseudo classes and pseudo elements are used to modify parts that are not in the document tree, such as the first letter of a sentence or the first element in a list.

pseudo-classes

Pseudo-classes are used to add styles to existing elements when they are in a state that changes based on user behavior. Hover, for example. Although it is similar to normal CSS in that it can style existing elements, it can only style elements in a state that the DOM tree cannot describe, so it is called pseudo-classes

Pseudo elements

Pseudo-elements are used to create elements that are not in the document tree and to add styles to them, such as :before. Although the user can see this, he is not actually in the document tree.

The difference between

Pseudo-classes operate on elements that already exist in the document tree, while pseudo-elements are elements that create a document outside the tree. Thus, the difference between a pseudo class and a pseudo element is whether an element outside the document tree is created

The CSS specification uses two double colons :: to denote pseudo-elements and a colon: to denote pseudo-classes. For example :: :before, :hover

17. Absolute positioning

  • If the parent element is block-level, the child element is set to the edge of the parent’s inner margin
  • If the parent element is inline, the child element is set to the content boundary of the parent element

Attach the cascading context table

18. The window. The onload, doument. The difference between onload

  • Window.onload: triggered when all the DOM, style sheets, scripts, images, and Flash on the page have been loaded
  • Document. onload: The DOM is loaded, but nothing else

19. Event delegation

Event delegate is an element response time (click, keydown….) Delegate to another element. In general, the time of one or a group of elements is delegated to the parent or outer element. It is the outer element that binds the event. When the event responds to the element that needs to be bound, it will trigger the binding event of its outer element through the event bubble mechanism, and then execute the outer function

  • Things like keyDown, onclick, mouse events, keyboard events, events that support bubbling have event delegates
  • Interface events such as: change, submit do not have event proxies

The event bubbling

The event model is divided into three phases

  • Capture phase: In an event bubbling model, the capture phase does not respond to any events
  • Target phase: The target phase is when the event responds to the lowest element that triggers the event
  • Bubbling stage: In the bubbling stage, the triggered response of the event will extend from the lowest target layer by layer to the outermost element (root node). The event broker uses the mechanism of event bubbling to bind the event that needs to be responded by the inner layer to the outer layer

Advantages of event delegation

  1. Reduce memory consumption If you have a list with many Li’s, it would be a waste of memory to bind events to each of them. It is better to bind this time to the outer layerulUpper unified treatment
<ul id="list"> <li>item 1</li> <li>item 2</li> <li>item 3</li> ...... <li>item n</li> </ul> // ...... I have li in the middleCopy the code

So event delegate can greatly reduce memory consumption and save efficiency

  1. Dynamically bind Events If we need to dynamically add or remove elements from a list, we have to re-bind events every time they change. This is not a problem with event delegates, because events are bound to parent elements and have nothing to do with whether the target element is added or deleted.

So event delegates can bind time dynamically, reducing a lot of rework

window.onload = () => {
  const list = document.getElementById('list')
  list.addEventListener('click'.function (event) {
    console.log(event.target)
  })
}

<ul class="list" id="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
Copy the code

The time it takes to click on the LI tag will bubble up to ul, and the binding method will begin

Pay attention to

Case analysis:

  • Have got the node, first capture, not just up bubbling search
  • Node.addeventlistener (‘event’,callback,bubble or capture); Who calls first who executes first

20. Implementation principle of Instanceof

while (x.__proto__) {
  if (x.__proto__ === y.prototype) {
    return true
  }
  x.__proto__ = x.__proto__.__proto__
}
if(x.__proto__ === null){
  return false
}
Copy the code

Determines whether the x object is an instance of y, searches the prototype chain, and returns true if found

21. The inheritance

  • Prototype inheritance
Student.prototype = new Person('b')
Student.prototype.constructor = Student
Copy the code

Disadvantages:

  1. Subtypes cannot pass parameters to supertypes
  2. Subclass methods must be written innew PersonBack, otherwise it’ll be covered
  • Class type inheritance
function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}
Copy the code

Disadvantages:

  1. There is no prototype, and Parent. Call is executed every time it is created
  • Combination of inheritance
function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}

Child.prototype = new Parent();      
Child.prototype.constructor = Child;
Copy the code

Disadvantages:

  1. The superclass constructor is called twice
  • Parasitic combination
function Person(name) {
  this.name = name
}

Person.prototype.a = function () {
  console.log('person a')
}

Person.prototype.b = function () {
  console.log('person b')}function Student(name, superName) {
  Person.call(this, superName)
  this.name = name
}

Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student

Student.prototype.b = function () {
  console.log('student b')}const person = new Person('p')
const student = new Student('s')

console.log(person)
console.log(student)

person.a()
person.b()
student.a()
student.b()

console.log(student instanceof Person)
Copy the code

22. for… In and for… of

  • for… in for… In iterates over all properties of the traversable object
const arr = [5, 4, 3, 2, 1]
arr.name = 'name'

for(let i inArr){console.log(I) // 0 1 2 3 4 name(string index)}Copy the code

The output is 0, 1, 2, 3, 4 name, because we added a name attribute to arr, for… In will also iterate over it

So the for… In is generally used to traverse an object and its value is its key value

  • for… of
const arr = [5, 4, 3, 2, 1]
arr.name = 'name'

for(let i inArr){console.log(I) // 0 1 2 3 4 name(string index)}Copy the code

The output is 5, 4, 3, 2, 1, for each of the values in the array

conclusion

  • for… Of uses iterator groups/array objects/strings/maps/sets etc. to have iterator objects, but cannot iterate over objects because objects have no iterator objects. He can use break, continue, return
  • for… In to iterate over the object, or useObject.keys()
  • for… In iterates over the array index (key name), for… Of is the value of the array

23. Array flattening

const test = [
  [1.2.2],
  [3.4.5.5],
  [6.7.8.9[11.12[12.13[14]]]], 10
]

// The above array is flat sorted and de-duplicated
/ / [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

/ / the recursive version
function flat(arr) {
  let list = []
  arr.forEach(item= > {
    if (Array.isArray(item)) { list.push(... flat(item))// list = list.concat(flat(item))
    } else {
      list.push(item)
    }
  })
  return list
}

const res1 = [...new Set(flat(test))].sort((a, b) = > a - b)

/ / ES6 version
const res2 = [...new Set(test.flat(Infinity))].sort((a, b) = > a - b)

console.log(res1)
console.log(res2)
Copy the code

24. Front-end performance optimization

Csspod.com/frontend-pe…

When writing

  • Be aware of memory leaks when writing code (timers, event listeners, closures, global variables, DOM references, etc.)

  • Do not use table layouts, CSS expressions and other backflow-causing styles in the CSS section. Enable 3D hardware acceleration (perspective, Backface-visibility fix flashing).

  • In js part, do not frequently modify the style, operate DOM, use anti-shake throttling, etc., and put the script at the bottom of the page

  • Webpack can compress JS, CSS, separate common resources such as UI component libraries, and configure components to load on demand (import() implementation).

  • The browser part can be set to cache, using CDN

  • Pictures can be compressed pictures, using webP format, Sprite, etc., pictures can be lazy when loading and other methods

  • The React section can use shouldComponentUpdate, react. Memo, pureComponent, and list elements to set keys. Bind functions from constructor, etc

  • Nginx can be configured with load balancing and multiple servers can use Redis to hold sessions

  • The page content

    • Reduce the number of HTTP requests
    • Reducing DNS queries
    • Avoid redirection
    • Caching Ajax requests
    • Lazy loading
    • preloaded
    • Reduce the dom element count
    • Divide different content into different domain names
    • Use iframe as little as possible
    • Avoid 404 errors
  • The server

    • Use the CDN
    • Add the Expires or cache-control response header
    • To enable Gzip
    • Configure the Etag
    • Early output buffering
    • Ajax requests use the GET method
    • Avoid image SRC being empty
  • Cookie

    • Reduce cookie size
    • Static resources use cookieless domain names
  • Css

    • Put the style sheet in<head>In the
    • Don’t use CSS expressions
    • use<linkInstead of@import
    • Don’t use filter
  • JavaScript

    • Place the script at the bottom of the page
    • Use external JavaScript and Css
    • Compress JavaScript and Css
    • Avoid duplicate scripts
    • Reduce DOM manipulation
    • Use efficient time processing
  • The picture

    • To optimize the image
    • To optimize the CSS Sprite
    • Do not zoom images in HTML
    • Use a small, cacheable favicon.ico
  • The mobile terminal

    • Keep a single file smaller than 25KB
    • Package content as a multipart document

25. Js to achieve animation

Slide div smoothly from fast to slow without using cSS3 properties


      
<html>

<head>
  <script>
    window.onload = (a)= > {
      var element = document.getElementById('t');

      function step(timestamp) {
        console.log(timestamp)
        var progress = timestamp;
        // element.style.left = (progress / 30) * (10 - progress / 1000) + 'px';
        element.style.left = Math.pow(progress / 5.. 5) * 40 + 'px';
        if (progress < 5000) {
          window.requestAnimationFrame(step);
        } else {
          window.cancelAnimationFrame(step)
        }
      }

      window.requestAnimationFrame(step);
    }
  </script>
  <style>
    .container {
      position: relative;
      width: 1000px;
    }

    #t {
      position: absolute;
      width: 50px;
      height: 50px;
      background: red;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="t"></div>
  </div>
</body>

</html>
Copy the code

26. Implement the AutoComplete property

There is an input field that simulates the autocomplete effect when typing a keyword


      
<html>

<head>
  <script>
    window.onload = (a)= > {

      const input = document.getElementById('input')
      const words = ['the zhuhai'.'guangzhou'.'Shanghai'.'hangzhou'.'chengdu']
      input.addEventListener("input", debounce(function (e) {
        const value = e.target.value
        const index = words.findIndex((item) = >value && item.indexOf(value) ! = =- 1)
        if(index ! = =- 1) {
          e.target.value = words[index]
        }
      }, 500))

      function debounce(fn, wait = 500) {
        let timeout = null
        return function () {
          if (timeout) {
            clearTimeout(timeout)
          }
          timeout = setTimeout((a)= > {
            fn.apply(this, [...arguments])
          }, wait)
        }
      }
    }
  </script>
  <style>
  </style>
</head>

<body>
  <input id="input" />
</body>

</html>
Copy the code

27. Deep copy code

const deepClone = (obj) = > {
  let result = null
  if (typeof obj === 'object') {
    result = Array.isArray(obj) ? [] : {}
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          result[key] = deepClone(obj[key])
        } else {
          result[key] = obj[key]
        }
      }
    }
  } else {
    // If it is not an object or array, it is assigned directly
    result = obj
  }
  return result
}
Copy the code

Or use native methods

JSON.parse(JSON.stringify(obj))
Copy the code

28. Out-of-order algorithm

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Simple version of

arr.sort((a)= > Math.random() - 0.5)
Copy the code

Shuffle algorithm

const shuffle = (arr) = > {
  let len = arr.length
  while (len > 1) {
    let index = Math.floor(Math.random() * len--);
    [arr[index], arr[len]] = [arr[len], arr[index]]
  }
  return arr
}
Copy the code

29. Array deduplication

Const arr = [1, 1, 1, 2, 3, 4, 5, 5, 3, 2, 1, 1

[...new Set(arr)]
Copy the code

Cycle version

const removeDrop = function () {
  const result = []
  const map = {}
  arr.forEach((item) = > {
    if(! map[item]) { map[item] =true
      result.push(item)
    }
  })
  return result
}
Copy the code

30. React Key functions

An overview of the

Key is used to help React identify what has been changed, added, or removed. The key value needs to be stable, because react triggers a UI rerendering if the key changes.

  • Uniqueness: The key value must be unique, and if it is identical, a warning is thrown, and only the element with the first duplicate key value is rendered. React will assume that all subsequent components with the same key are the same.

  • Unreadable: Although a key is defined in a component, it cannot be retrieved from a child component

Changing a component’s key can destroy the previous component and create a new one

Pay attention to

If the array is dynamically changed, such as adding new elements, deleting or rearranging the array, if index is used as the key value, the wrong data will be displayed

{this. State. Data. The map (= (v, independence idx) > < Item key = v = {n} {independence idx} / >)} / / at the beginning: ['a'.'b'.'c']=>
<ul>
    <li key="0">a <input type="text"/></li>
    <li key="1">b <input type="text"/></li>
    <li key="2">c <input type="text"/></li> </ul>'c'.'b'.'a'] =>
<ul>
    <li key="0">c <input type="text"/></li>
    <li key="1">b <input type="text"/></li>
    <li key="2">a <input type="text"/></li>
</ul>
Copy the code

If the key is the same and the component changes, only the changed properties will be updated. If the key is different, the previous component will be destroyed and the whole component will be re-rendered

The scenario where index is used as the key

Page 1 <ul> <li key="0"</li> <li key="1"</li> <li key="2"</li> </ul> page 2 <ul> <li key="0"< span style = "box-sizing: border-box! Important"1"</li> <li key="2"</li> </ul>Copy the code

After the page is turned, the subcomponent values change, but the key stays the same, and only updates, not rerenders, occur

anti-patterns

Here’s an example where react will automatically use an index as the key if we don’t add a key

let arr = ['first'.'second']; // List1 and list2 are equivalent const list1 = arr.map(item => <p>{item}</p>); list1 = arr.map(item => <p>{item}</p>); const list2 = arr.map((item, index) => <p key={index}>{item}</p>);Copy the code

Then we add an element to the end of the array. React diff doesn’t change the keys 0 and 1, so the UI operation just adds an element to the end

But if you add an element at the beginning

<! -- before --> <p key="0">first</p>
<p key="1">second</p> <! -- after --> <p key="0">zero</p>
<p key="1">first</p>
<p key="2">second</p>
Copy the code

So the elements’ keys are changed so that each element is re-rendered, and performance is greatly affected

conclusion

In short, change the key value to heavy rendering component is a complicated componentWillReceiveProps – compared with life cycle – it is low cost.

31. The React series

When the render function of the component is called

Each state change causes the render function to be called, but the DOM of the page does not necessarily change

Component life cycle

  1. Initialization Phase (Mounting)
  2. Updating phase
  3. Destruction Stage (Unmounting)

Initialization phase:

  • Constructor (): Used to bind events and initialize state
  • ComponentWillMount (): Components to be mounted, called before render, each component is called before render, usually with state. It can be called on the server side
  • Render (): Used to render the DOM
  • ComponentDidMount (): Called after Render and after all of the subcomponents are render, usually for asynchronous requests because components are initialized

Update phase:

  • ComponentWillReceiveProps (nextProps) : here you can get the change of state, the state can be set through setState method here
  • ShouldComponentUpdate (nextProps, nextState): Its return value determines whether the next declaration cycle will be called, returning true by default
  • ComponentWillUpdate (): You can’t change state here or you’ll get stuck in an infinite loop
  • ComponentDidUpdate (): Similar to componentDidMount(), this is where Dom operations are performed and network requests are made

Destructor phase

  • ComponentWillUnmount (): Performs cleanup, such as canceling network requests and clearing event listeners

Virtual Dom

React only compares nodes in the same layer, not across layers. The procedure is divided into two steps:

  • The object is first traversed from top to bottom and left to right, the depth of the tree, and each node is indexed to facilitate the final rendering of the differences
  • Once the node has child elements, determine if the child elements are different

The realization of Virtual Dom algorithm mainly consists of three steps

  1. Create DOM objects through JS simulation
  2. Convert the virtual DOM into a real DOM and insert it into the page
  3. When changes occur, the difference between two trees is compared and the difference object is generated
  4. Render the differences into the real DOM based on the differences object

SetState synchronization? Asynchronous?

  1. SetState is only asynchronous in synthetic events (onClick, onChange, etc., in JSX) and hook functions, and synchronous in both native events and setTimeout
  2. SetState “asynchronous” is not to say that the internal are implemented by the asynchronous code, actually perform process and code are synchronized, just synthetic events and hook function call order before update, resulting in synthetic events and hook function can not immediately get the updated value, of course, you can also use setState parameters to obtain the second
  3. Batch update optimization of setState is based on “asynchrony” (composite events, hook functions). Batch update is not performed in native time and setTimeout. In “asynchronous”, if setState is performed on a value for several times, the batch update policy of setState will overwrite it and take the last execution. If multiple different values are setState at the same time, it will be updated in a combined batch
class App extends React.Component {
  state = { val: 0 }

  componentDidMount() {
    this.setState({ val: this.state.val + 1 })
    console.log(this.state.val)

    this.setState({ val: this.state.val + 1 })
    console.log(this.state.val)

    setTimeout(_ => {
      this.setState({ val: this.state.val + 1 })
      console.log(this.state.val);

      this.setState({ val: this.state.val + 1 })
      console.log(this.state.val)
    }, 0)
  }

  render() {
    return <div>{this.state.val}</div>
  }
}
Copy the code

Because setState is asynchronous in the hook function, the first two times we can’t get the value of val, so we print 0. Then by setTimeout, the setState has already been updated, and since it is batch update, we only execute the last time, so by setTimeout, val is 1. Because setTimeout is synchronous, the first time is 2 and the second time is 3

32. How do you React

What happens after setState is called

After the setState function is called, React merges the passed argument object with the current state of the component and triggers a Reconciliation process, which builds the React element tree based on the new state in a relatively efficient way and rerenders the entire UI. React gets the element tree, calculates the node differences between the new tree and the old tree, and minimizes the interface rerendering based on the differences. In the difference algorithm, React is able to know with relative precision what has changed, which ensures that updates are made on demand rather than completely rerendered

React Element vs. Component

React Elements are data structures that describe what is visible on the screen and are object representations of the UI. The React Component, on the other hand, is a function or class that takes arguments and returns a React Element

When do you prefer using Class Component over Functional Component

Select Class Component when the Component needs internal state and lifecycle functions; otherwise use Functional Component

What does refs do in React

Refs is a React handle that provides safe access to a DOM element or component instance. You can add the ref attribute to the element and then accept the handle in the DOM tree in the callback function

React keys

React keys are auxiliary identifiers used to track which elements are changed, added, or removed from a list. Ensure that keys are unique. The React Diff algorithm uses key values to determine whether elements are new or moved, thus reducing unnecessary element re-rendering. React also uses Key values to determine the relationship between elements and states

The difference between controlled and uncontrolled components

  • Controlled components are those that centrally manage form data with React and use setState to update form values
this.state = {
    value: ' '}... handleChange = (e) => { this.setState({ value: e.target.value }) } ... <input onChange={() => this.handleChange} />Copy the code
  • Uncontrolled components are the dom that holds the form data, and we can use refs to manipulate dom elements
handleChange = () => {
    console.log(this.input.value)
}

...

<input refs={(input) => this.input = input}
    onChange={() => this.handleChange} />
Copy the code

Although uncontrolled components are easier to implement, there are times when we need to work with data and it is easier to use controlled components

Which step in the declaration cycle should make the Ajax request

Should be componentDidMount()

  • The Fiber harmonic algorithm affects the number of times compnentWillMount is triggered, and if it is placed inside, it may make multiple Ajax requests
  • If we put it in another life cycle, assuming we get the result of the Ajax request and add it to the component’s state, the unmounted component will report an error. And in thecomponentDidMountYou wouldn’t have these problems

ShouldComponentUpdate what is shouldComponentUpdate and why is it so important

ShouldComponentUpdate allows us to manually determine whether a component is updated or not, thus avoiding unnecessary updates to render

React event handling logic

To address cross-browser compatibility issues, React encapsulates browser-native events as synthesized events passed into the event handler. Composite events use the same interface as native time, but they mask the details of the underlying browser to ensure consistent behavior. Instead of attaching events to child elements, React sends all events to the top-level document for processing

All events on JSX are bound to document, which not only reduces memory consumption, but also removes events uniformly when a component is destroyed

If we don’t want the event to bubble, it should be event.preventDefault instead of event.stopPropagation

What is the difference between createElement and cloneElement

The createElement function is used by JSX to create an Element after compilation, while cloneElement is used to copy an Element and pass in new Props

What does the second argument to the setState function do

SetState is a callback function that is called when the setState call is complete and the component starts to re-render to determine if the update rendering is complete

Why does the virtual DOM improve performance

Virtual DOM is equivalent to adding a cache between JS and real DOM. Dom DIff algorithm is used to avoid unnecessary DOM operations, thus improving performance. The steps are as follows:

  1. Use JS to simulate creating a DOM
  2. Build the real DOM from this virtual DOM and insert it into the page
  3. When the status changes, the difference between the two object trees is compared and the difference object is generated
  4. Update according to the difference object

The diff algorithm

  • Break the tree down into layers, comparing only its peers
  • Add a unique key attribute to each element of the list structure for easy comparison
  • If the components are of the same type, follow tree Diff
  • If it is not the same class, the component is judged to be a dirty Component and replaces all child nodes under the entire component without spending time comparing the differences
  • The merge operation, called setState, marks components as dirty. At the end of an event loop, React checks that all components marked dirty are redrawn. This way the DOM is updated only once, saving performance
  • Select subtree rendering and use shouldComponentUpdate to improve diff performance

Three optimization strategies of diff algorithm

  1. Tree optimization strategy
  • Hierarchical control, diff tree at the same level only compare nodes at the same level
  • If a node does not exist, the node is deleted
  • Comparisons across hierarchies are created or deleted accordingly
  1. Component optimization strategy
  • If yes, use Tree diff
  • If they are not of the same type, they are considered dirty Component. To replace the child nodes under the entire component
  • For the same type of component, shouldComponentUpdate can be used to manually terminate the diff algorithm and speed up rendering
  1. Element optimization strategy
  • Insert: A new node needs to be inserted
  • Move. The node itself exists and needs to be moved
  • Delete, the same structure, different content, no need to directly reuse, need to delete reconstruction
  • Based on the unique mark key to calculate, fast positioning

React Performance Optimization

  • Use shouldComponentUpdate to avoid unnecessary DOM manipulation
  • Use keys to help React recognize minimal changes to list subcomponents
  • React.memo
  • SSR
  • Do not use the arrow function or bind in render, instead call bind in constructor

The pit of the react

  • componentWillUnmounted
  • Enclosing setState out of sync
  • PureComponent does not update prop if it is a multi-level object

Brief introduction to Flux idea

The biggest feature of Flux is that data flows in one direction

  1. User access to View
  2. The View emits the user’s Action
  3. Dispatcher receives Action requesting Store to update accordingly
  4. After the Store is updated, a “change” event is emitted
  5. View updates the page after receiving the “change” event
  6. Using anti-shake requires keeping event referencesevent.persist()

Show the differences between Presentational Component and Container Component

  • The presentation component cares about what the component looks like, specifically receiving data and callbacks through props, and generally not having its own state
  • Container components care about how components behave. Container components provide data and behavior for presentation components or other container components, and generally have their own state because they are data sources for other components

What is the difference between the component’s state and its properties

  • State is a data structure for default values of data required when a component is mounted. State is generally changed by user event behavior
  • Props is a component configuration that is transmitted from a parent component to a child component. It cannot be changed.

What are higher-order components

A higher-order component is a function that takes a component as an argument and returns a newly formed component. HOC runs reuse code, logic, and bootstrap abstractions. The most common is Redux’s connect function. HOC’s best approach is to share behavior between components. If you find a place where a lot of code is used to do one thing, consider refactoring to HOC

Why is it recommended that the setState argument be a callback rather than an object

Because updates to state and props can be asynchronous, they cannot be relied on to calculate the next state

Is there any other way to bind this in the constructor

Arrow functions can be used in callbacks, but the problem is that a new callback is created each time you render

Why is super called in the constructor

Because subclasses cannot use this until super() is called

React builds components in three ways

React. CreateClass, ES6 classes, stateless functions

Difference between useEffect and useEffect

Different call times

  • UseEffect is performed after the component has been rendered
  • UseLayoutEffect is executed before the component is rendered

UseLayoutEffect is executed before useEffect

Implement the use estate and useEffect

React uses a form like a single linked list instead of an array, using next to concatenate all hooks sequentially

UseEffect features:

  1. Two arguments: a callback function and a dependent array
  2. If the dependent array does not exist, the callback is fired for each render
  3. If the dependency array exists, the callback is executed only if it changes

let arr = [] // An array to store each hook
let index = 0 // access the corresponding position of each hook

function useState(init){
    arr[index] = arr[index] || init // If so, use the previous value
    const cur = index // Set a variable to store the current index
    
    function setState(newState){
        arr[cur] = newState
        render() // Render, the page triggers an update
    }
    
    return [arr[index++], setState]
}

function useEffect(callback, deps){
    consthasNoDeps = ! deps// If there are no dependencies, update each time directly
    const lastDeps = arr[index] // Get the last dependency array
    consthasChangeDeps = lastDeps ? ! deps.every((e, i) = > e === lastDeps[i]) // If each term is the same
      : true
    if(hasNoDeps || hasChangeDeps){
        callback()
        arr[index] = deps
    }
    index++
}
Copy the code

The React of new features

  1. Lazy and Supense
import React, {Component, lazy, Suspense} from 'react'

const About = lazy(() => import(/*webpackChunkName: "about"* /'./About.jsx'))

class App extends Component {
  render() {
    returnIn suspense < suspense fallback={<div> loading... </div>}> < girl >< girl >< girl >< girl >< girl > --<About></About>--> </div> ); }}export default App;
Copy the code
  1. Error boundaries
class App extends Component {
  state = {
    hasError: false,
  }
  static getDerivedStateFromError(e) {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return <div>error</div>
    }
    return (
      <div>
        <Suspense fallback={<div>Loading...</div>}>
          <About></About>
        </Suspense>
      </div>
    );
  }
}
Copy the code
  1. Memo React.memo applies to function components, not class components

ShouldComponentUpdate is similar to pureComponent, but the shouldComponentUpdate provided by pureComponent only compares whether the props passed in have changed or not, and does not update if the internal value changes. For example,

class Foo extends PureComponent {
  render () {
    console.log('Foo render');
    return<div>{this.props.person.age}</div>; } person: {count: 0, age: 1} // person. Age ++ should trigger the update, but not because the first level of props is not changedCopy the code

At this point we can use the Memo to optimize

const Foo = memo(function Foo (props) {
  console.log('Foo render');
  return <div>{props.person.age}</div>;
})
Copy the code

The first memo argument is a function component, and the second is a function similar to shouldComponentUpdate

(nextProps, nextState)=>{
    
}
Copy the code
  1. The advantage of the hook
  • Function components do not have this problem
  • Custom hooks facilitate reuse of state logic
  • Separation of side effects concerns
  • It’s easier to write and understand
  1. The disadvantage of the hooks
  • Hooks may run more often than you expect
  • UseEffect dependencies are somewhat difficult to maintain

React status upgrade

Data that is common in child components resides in parent components

// Class AllInput extends React.Com {constructor(props) {super(props) this. State = {content:' ' }
        this.handleContentChange = this.handleContentChange.bind(this)
    }
    handleContentChange(newContent) {
        this.setState({ content: newContent })
    }
    
    render() {
        return( <div> <Input content={ this.state.content } onContentChange={ this.handleContentChange }/> <br /><br /> <Input Content ={this.state.content} onContentChange={this.handleconTentChange}/> </div>)}}/ / child component class Input extends React.Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this) } handleChange(e) {setState (method of modifying data). This props. OnContentChange (e. arget. Value)}render() {
        return (
            <input type='text' value={ this.props.content } onChange={ this.handleChange } />
        )
    }
}
Copy the code

Higher-order functions

A higher-order function is something that takes one or more functions and then returns a function

There are two main functions

The property broker

Property brokers have three common functions

  • Operating props
function HigherOrderComponent(WrappedComponent) {
    return class extends React.Component {
        render() {
            const newProps = {
                name: 'Big chestnut',
                age: 18,
            };
            return<WrappedComponent {... this.props} {... newProps} />; }}; }Copy the code

This way, you can pass custom props to the child components

  • Out of the state
// Common Component Login import React, {Component} from'react';
import formCreate from './form-create';

@formCreate
export default class Login extends Component {
  render() {
    return (
      <div>
        <div>
          <label id="username"> Account </label> <input name="username"{... this.props.getField('username')}/>
        </div>
        <div>
          <label id="password"> Password </label> <input name="password"{... this.props.getField('password'}/> </div> <div onClick={this.props. HandleSubmit}> Submit </div> <div>other content</div> </div>)}}/ /HOC import React, { Component } from'react';

const formCreate = WrappedComponent => class extends Component {

  constructor() {
    super();
    this.state = {
      fields: {},
    }
  }
  onChange = key => e => {
    const { fields } = this.state;
    fields[key] = e.target.value;
    this.setState({
      fields,
    })
  }
  handleSubmit = () => {
    console.log(this.state.fields);
  }
  getField = fieldName => {
    return {
      onChange: this.onChange(fieldName),
    }
  }
  render() { const props = { ... this.props, handleSubmit: this.handleSubmit, getField: this.getField, }return (<WrappedComponent
      {...props}
    />);
  }
};
export default formCreate;
Copy the code

For example, you can pull the state out of the input box

  • Operating refs
import React, { Component } from 'react';

const refHoc = WrappedComponent => class extends Component {

  componentDidMount() {
    console.log(this.instanceComponent, 'instanceComponent');
  }

  render() {
    return (<WrappedComponent
      {...this.props}
      ref={instanceComponent => this.instanceComponent = instanceComponent}
    />);
  }
};

export default refHoc;
Copy the code

Refs can no longer be used on stateless components (function-type components) because stateless components have no instances

Reverse inheritance

function HigherOrderComponent(WrappedComponent) {
    return class extends WrappedComponent {
        render() {
            returnsuper.render(); }}; }Copy the code

Reverse inheritance is a function that takes a component as an argument, returns a class that inherits that component, and calls super.render() in that class’s render.

  • You can manipulate state, but it can be difficult to maintain
  • Rendering hijacked

We can control the render of components, conditionally display components for example

  1. Conditions apply colours to a drawing
function withLoading(WrappedComponent) {
    return class extends WrappedComponent {
        render() {
            if(this.props.isLoading) {
                return <Loading />;
            } else {
                returnsuper.render(); }}}; }Copy the code

This allows you to conditionally control component rendering

  1. Modify render output
  //hijack-hoc
  import React from 'react';

  const hijackRenderHoc = config => WrappedComponent => class extends WrappedComponent {
    render() {
      const { style = {} } = config;
      const elementsTree = super.render();
      console.log(elementsTree, 'elementsTree');
      if (config.type === 'add-style') {
        return<div style={{... style}}> {elementsTree} </div>; }returnelementsTree; }};export default hijackRenderHoc;
  
  //usual
  @hijackRenderHoc({type: 'add-style', style: { color: 'red'}})
  class Usual extends Component {
    ...
  }
Copy the code

The problem with HOC

  • Static method loss
  • The refs attribute cannot be transparently transmitted
  • Reverse inheritance does not guarantee that the child component is fully parsed

HOC conventions

  • Props stay consistent
  • Refs cannot be used in a functional (stateless) component because it does not have one
  • Do not change child components
  • You can add a wrapper name to facilitate debugging
  • Don’t use HOC in render

Application scenarios

  1. Access control
  2. Page reuse

React Component Communication

  • The parent component passes the child component props
  • The child component calls the parent component’s callback function
  • Use the context
  • Use EventEmitter

Why React and not Vue

  • React is a functional idea, where all the state logic and stuff is passed in as arguments, right
  • Do everything with JS, CSS can also use JS
  • The community is powerful, and a lot of the functionality comes together
  • The UI library is great
  • JSX makes components more readable and allows you to see the structure between components more clearly
  • Support for server-side rendering, better SEO and rendering performance

React and MVVM

  • M(ODAL): Data such as life cycle and state in the corresponding component
  • V (IEW): Corresponding to the virtual DOM generated real DOM, as well as style, etc
  • V(IEW)-M(ODAL): JSX in the corresponding component converts the virtual DOM to the real DOM through the DIFF algorithm

React one-way binding versus bidirectional binding

Generally, only UI form controls require bidirectional binding.

  • When the UI form of one-way binding values changes, we need to manually update the state, that is, set the listening eventonChangeEtc.
  • Bidirectional binding updates automatically

One-way binding data is easier to track, manage and maintain when forms interact a lot, but requires more code

33. CSRF and XSS

The difference between

  • CSRF requires post-login operations, but XSS does not
  • CSRF is to request the page API to perform illegal operations, XSS is to modify the page content by embedding JS scripts into the current page

CSRF

A CSRF attack occurs when a user logs in to a website and generates a cookie. If a new URL is opened and the url returns some malicious requests, this is a CSRF attack

  • The prevention of
  1. Verify the HTTP reference
  2. Add token authentication to request address
  3. Add token validation to the request header

XSS

Cross-site scripting attacks are generally carried out by inserting malicious JS code into web pages. There are three main categories:

  1. Reflexivity: XSS code attacks in the request URL
  2. Stored: Attack scripts are saved to the server for propagation
  3. Dom: Modifies the page content using the DOM
  • The prevention of
  1. Input filtering: for example, filtering<script>Etc.
  2. Output escape: for example will<.>./Such characters are converted using escape symbols
  3. Use HttpOnly: Make cookies inaccessible to JS scripts
  4. Try to use post and limit the length of get

conclusion

  • Tokens are added to prevent CSRF, not XSS
  • CSRF attacks because browsers automatically carry cookies instead of tokens

34. LocalStorage and sessionStorage and cookies

localStorage

The life cycle is permanent and can only hold string types

  • Cross-domain implementation using iframe and postMessage

sessionStorage

The life cycle is that the current window or TAB is not closed, once closed, the stored data is cleared

cookie

The cookie life cycle is valid until the expiration time and is shared between all same-origin Windows under the same browser

The attribute of the cookie

  • Name: Must define the name of the cookie
  • Value: Specifies the value of the cookie
  • Expires: Specifies the expires time. The value is in UTC or GMT format. If the cookie is not set, it is only valid for the current session and will be deleted when the browser window is closed
  • Domain: specifies the domain name of the cookie. The default value is the domain name when the cookie is set. The specified domain name must be part of the current cookie
  • The default path is the path of the web page requesting the cookie. The cookie will be sent only if the path attribute matches the path sent to the server, as long as the path attribute matches part of the path sent to the server, for examplepath=/blog, the path to be sent is/blogrollCan also. The path attribute takes effect only when domain attributes match
  • Secure: Indicates that cookies can be sent to the server only when the encryption protocol HTTPS is used. If the communication protocol HTTPS is used, cookies are automatically enabled
  • Max-age: specifies the cookie validity period. Max-age has a higher priority than expires
  • Httponly: The httponly property is used to make the cookie inaccessible to JavaScript, mainly to prevent the XSS tool from stealing the cookie

conclusion

  • Different browsers cannot share localStorage and sessionStorage
  • Different pages in the same browser can share the same localStorage (pages belong to the same domain name and port).
  • SessionStorage information cannot be shared between different tabs in the same browser

35. BFC and its role

A BFC is a format context, which is equivalent to a container in which the elements and the outside do not affect each other.

  1. HTML root element
  2. Float float
  3. Absolutely positioned elements position: fixed | | absolute
  4. Overflow visiable
  5. Display table, inline-block, flex

The main function of BFC is

  1. Remove the floating
  2. Prevent margin overlap between adjacent elements in the same BFC
  3. BFC elements and float elements do not overlap
  4. The BFC takes the floating element into account when calculating the height

36. Realize (5).add(3).minus(2)

Number.prototype.add = function(n) {
  return this + n;
};
Number.prototype.minus = function(n) {
  return this - n;
};
Copy the code

37. Continuous assignment

Case 1:

var a = 3;
var b = a = 5;

=

var a = 3
var a = 5
var b = a
Copy the code

So we end up with both a and B being 5

Example 2:

var a = { n: 1 }
var b = a

a.x = a = { n: 2 }
Copy the code

At first a and B both refer to {n:1}, and then to the assignment statement if the assignment statement occurs. It will perform one step ahead of =, so let’s create a space for a.x, which means that a and B are now equal to

{
  n: 1,
  x: {
      n: 2
  }
}
Copy the code

And then the assignment to A, a is now going to be

{
    n: 2
}
Copy the code

38. Display: none, visibility: hidden and opacity: 0

  • display: none: does not take up space, cannot be clicked, is generally used to hide elements, will cause backflow, high performance overhead, non-inherited attributes, descendant node changes cannot be displayed (parent element is None)
  • visibility: hidden: Occupies space, cannot be clicked, display will not lead to page structure change, will not spread, belongs to the redraw operation, is inherited attribute, descendant nodes can be modified to display
  • opacity: 0: Takes up space, can be clicked, usually used with Transition

39. Performance of for and forEach

For is faster than forEact because

  • For has no additional function call stack, and no context

40. The react to the router<Link><a>What is the difference between

Tag, which only updates the content of the matching page, not the entire page. He uses’ history ‘to jump, changing the URL but not refreshing the page

41. Execution context

  • Global execution context: The default context, any code that is not inside a function is in the global context. It does two things: it creates a global window object and sets this to the global object. A program has only one global object
  • Function execution context: Each time a function is called, a new context is created for that function. Each function has its own context, but it is created when the function is called. Function contexts can have as many as they want, and each time a new execution context is created, it performs a sequence of steps in the order defined
  • The Eval function executes the context: perform inevalThe code inside a function has its own execution context

42. The execution stack

An execution stack is a call stack, a stack of lifO data structures that store the execution context created when the code is run

let a = 'Hello World! ';

function first() {
  console.log('Inside first function');
  second();
  console.log('Again inside first function');
}

function second() {
  console.log('Inside second function');
}

first();
console.log('Inside Global Execution Context');
Copy the code

43. Create execution context

There are two stages

  • Create a stage
  • Execution phase

Create a stage

The execution context is created before the code executes, and three things happen

  1. This binding
  2. Create the lexical environment component
  3. Create the variable environment component

This binding

In the context of global execution, this refers to a global object

In the context of function execution, this depends on how the function is called. If it is invoked by a reference object, this will be set to that object. Otherwise it is a global object

let foo = {
  baz: function() {
  console.log(this);
  }
}

foo.baz();   // 'this'reference'foo'Because the'baz'/ / object'foo'calllet bar = foo.baz;

bar();       // 'this'Points to the global Window object because // does not specify a reference objectCopy the code

Lexical environment

Is something that uses code’s lexical nesting structure to define identifiers associated with specific variables and functions. Variable bindings used to store function declarations and let, const declarations

The variable environment

Also a lexical environment for storing var variable bindings

let a = 20;
const b = 30;
var c;

function multiply(e, f) {
 var g = 20;
 return e * f * g;
}

c = multiply(20, 30);
Copy the code

The function execution context is created only when multipy is called. Let and const are not initially associated with any value, but var is already set to undefined

44. Event loops

Tasks fall into two categories

  • Synchronization task
  • Asynchronous tasks

Macro task

  • The main body of code
  • setTimeout
  • setInterval
  • setImmediate
  • requestAnimationFrame

Micro tasks

  • process.nextTick
  • mutation.observer
  • Promise.then cath finally

45. The link and @ import

  • Link is an HTML tag, and @import is a CSS tag
  • Link loads when the page loads, while @import loads CSS after the page loads
  • Link does not have compatibility problems
  • Link has more weight

46. Margins overlap

  • When two adjacent margins are both positive, the folding effect is greater between them
  • The folding effect is greatest in absolute value when both adjacent margins are negative
  • Two margins, one positive and one negative, add up

47. Progressive enhancement and elegant improvement

  • Progressive enhancement: Build pages for older browsers to keep basic functionality, and then improve them for more advanced browsers to look and interact with each other
  • Elegant improvements: Build the full functionality from the start and then make it compatible with older browsers

Difference: Progressive enhancement is upward compatibility, elegant improvement is downward compatibility

48. Execute the function immediately

role

  • Do not break the global namespace
  • If needed, pass in the variable
(function(x){ console.log(x); } (12345))Copy the code

49. HTTP2.0 and HTTP1.1

HTTP2.0

  1. The basic unit of HTTP2.0 is binary. It used to be in text format, which is not very robust. Now it uses binary format, which is more convenient and more robust
  2. HTTP2.0 multiplexing, the multiple requests as multiple streams, request response data is divided into multiple frames, different streams in the frame staggered send, solve the TCP connection number, TCP connection is slow, so for the same domain name only to create a connection can be
  3. HTTP2.0 compresses headers, avoiding the transmission of duplicate request headers and reducing the size of the transmission
  4. HTTP2.0 server push: after the browser sends a request, the server actively sends the resources associated with the request, and the browser does not have to send subsequent requests.
  5. HTTP2.0 can set request priorities, which can resolve blocking problems

HTTP1.1

  • New headers such as etag and if-none-match are added to control the cache
  • Long connection, which can send multiple requests and responses over a TCP connection

50. The difference between CSS animation and JS animation

  • CSS performance is good
  • CSS code logic is relatively simple
  • Js animation control well
  • Js animation compatibility is good
  • Js can achieve more animation
  • Js can add events

51. Offset, Client, and Scroll properties

  • Client: padding + Content – scrollbar
  • Offset: padding + Content + boder
  • Scroll: padding + Actual content

52. Tore code by hand

  1. Enter the root node, print the label path, and the maximum value of data-v on the path
const root = document.getElementById("root");

function walk(node, path, max) {
  if(! node) {return;
  }
  path = [...path, node.tagName];
  max = Math.max(max, node.dataset.v);
  console.log(path, max);
  for (let child of node.children) {
    walk(child, path, max);
  }
}
walk(root, [], -1)

...

<div id="root" data-v="3">
  <p data-v="1">p1</p>
  <span data-v="2">
    span1
    <span data-v="4">span2</span>
    <span data-v="5">
      <p>1</p>
    </span>
  </span>
  <p data-v="99">p2</p>
</div>
Copy the code
  1. Implementing the compose function
var arr = [func1, func2, func3];
function func1(ctx, next) {
  ctx.index++
  next();
}
function func2(ctx, next) {
  setTimeout(function () {
    ctx.index++
    next();
  });
}
function func3(ctx, next) {
  console.log(ctx.index);
}

compose(arr)({ index: 0 });

function compose(arr) {
  return function (ctx) {
    if(arr.length ! = = 0) {let func = arr.shift()
      func(ctx, next)
    }
    function next() {
      if(arr.length ! = = 0) {let func = arr.shift()
        func(ctx, next)
      }
    }
  }
}
Copy the code
  1. A magnifying glass

IO /yinxin630/p…

Margin and padding for inline elements

  • Horizontal direction: horizontal direction, both effective
  • Padding-bottom and padding-top will show the effect, but the height will not spread out and will not affect the surrounding elements

54. Inline elements and block-level elements

  • Inline, block-level elements can be converted to each other
  • The inline elements are arranged on a horizontal line, and the block level is placed on a new line
  • Inline elements cannot be set to width, but line-height can be set.
  • Margin and padding do not work on the vertical direction of the inline element. The vertical direction of the padding is displayed but does not spread and does not affect other elements
  • The block level can contain inline elements and block-level elements, and inline elements can contain only inline elements and text

55. How are margin, padding, and Translate percentages calculated

  • Margin: measured by the width of the parent element
  • Padding: Calculated by the width of the parent element
  • Translate: It is calculated by its own width and height

56. Display: There are gaps between inline-block elements

Cause inline-block is inline externally and block internally, which resolves successive whitespace to a space

The solution

  • Delete the blank space
  • Parent element Settingsfont-size: 0
  • Parent element Settingsletter-spacing: -4px
  • Child element Settingsvertical-align: bottomRemoval of vertical clearance

57. The HTTPS principle

HTTP is a plaintext transmission, and every link of the transmission can be stolen or tampered with by a third party. In particular, HTTP data passes through the TCP layer and then through WIFI routers, carriers and target servers, all of which can be picked up and tampered with by middlemen, often referred to as man-in-the-middle attacks

HTTPS is an enhanced version of HTTP. Symmetric encryption and asymmetric encryption are used to protect the communication security between the browser and the server. Symmetric encryption algorithm Encrypt data + Asymmetric encryption algorithm Exchange key + digital certificate authentication = security

HTTPS consists of two parts: HTTP + SSL/TLS, which adds a layer of modules on TOP of HTTP to process encrypted information. Both the server and client are encrypted through TLS, so the transmitted data is encrypted

The encryption process

First the browser sends the server a client_RANDOM and an encrypted list of methods

The server accepts this and returns to the browser another random number server_random and the encryption method

Both now have three identical credentials: client_RANDOM, server_random, and encryption methods

This encryption method is then used to mix two random numbers together to generate a key that is used by the browser to communicate with the server

Symmetric and asymmetric encryption

  • Symmetric encryption is the simplest method, in which encryption and decryption use the same secret key. It has the advantage of ensuring the confidentiality of the message, but the disadvantage is that the key can be leaked

  • Asymmetric encryption means that if there are two keys A and B, the data packets encrypted with A can only be decrypted by B. Otherwise, the data packets encrypted with B can only be decrypted by A. When sending messages, the client encrypts them with the public key first, and the server decrypts them with the private key. But because the public key is not secret, it can be stolen and messages can be tampered with

Digital certificates and signatures

In order to solve the unsecurity of public key source in asymmetric encryption. We can solve this problem by using digital certificates and digital signatures.

First, a pair of keys is generated locally and the public key is used to apply for a digital certificate from the CA

  • Digital signature: After obtaining the information, the CA encrypts the information using the one-way hash algorithm and generates a digest. The CA encrypts the digest with its own private key. The result is a digital signature

  • Digital certificate: Finally, the CA combines the application information with the digital signature to create a digital certificate, which is essentially a public key

  • How digital certificates work:

  1. The client uses the CA’s public key to decrypt the digital certificate. If the source of the digital certificate is legitimate, the client obtains the information summary after the decryption succeeds. The client then generates a summary of the application information using the same hash algorithm as the CA.
  2. It is then compared with the decrypted summary, and if complete, it has not been tampered with. The client can then retrieve the server’s public key from the certificate and communicate with the server in secure asymmetric encryption. The server can also use this method to obtain the public key of the client

handshake

  1. The client requests HTTPS communication to send a random number, as well as encryption methods
  2. The server responds and sends the digital certificate (public key) and random number to the client
  3. The client TLS verifies the certificate, gets the public key, generates a random value if there is no problem, and encrypts it to the server with the public key
  4. The server decrypts it with the private key, obtains the symmetric key, and then transmits information through the key, and establishes the SSL connection channel
  5. The shared key exchange succeeds, and the client and server start encrypted communication
  6. disconnect
Client: Hello, I want to make an HTTPS request, please give me the public key server: ok, this is my certificate, with the encrypted public key client: after decryption, tell the server: This is my symmetric secret key. Server: OK, I know your secret key, I will use it to transmit.Copy the code

use

HTTPS encryption and decryption takes a long time and consumes resources. Therefore, HTTPS encryption and decryption do not need to be used unless security requirements are high

58. SetImmediate (), and the process. NextTick ()

  • SetTimeout: executes after the specified time
  • SetImmediate Is designed to execute immediately after the current polling phase is complete. SetImmediate is always called first if used within the same I/O loop. SetImmediate has the advantage that it executes before all timers if dispatched within the I/O cycle. The way it executes is at the end of the current task queue
  • Process. nextTick fires at the end of the current execution stack, before the next event loop, always before asynchrony.

Why use process.nexttick (), which allows the user to handle errors or retry requests before the event loop continues

59. Browser and Node event loops

Browser tasks are divided into macro tasks and micro tasks

  • Macro tasks: code in script, setTimeout, setInterval, I/O, UI render
  • Microtasks: Promise, Object.observe, MutationObserver

Nodes are classified into the following types:

  • Microtasks
  • NextTick: process. NextTick
  • Timers: Indicates various types of timers
  • I/O Callback: Whether there are callback functions for completed I/O operations, remnants from the previous round, that perform almost all callbacks, but not the close, timer, and setImmediate
  • Idle, prepare: Used only internally
  • Poll: Blocks waiting for new I/O events due to timers and timeout events
  • Check: Executes the setImmediate callback
  • Close callback: Closes all closing handles, some onclose events

Under the environment of the Node

Before the loop, the following is done:

  • Synchronization task
  • Make an asynchronous request
  • This section describes how to set the timer validity time
  • Executing process. NextTick ()

An operation performed in a loop:

  • Clear timers, nextTick, and microTask queues
  • Clear the I/O queue, the nextTick queue, and the microTask queue
  • Clear the Check queue, the nextTick queue, and the microTask queue
  • Clear the close queue, clear the nextTick queue, clear the microTask queue

The difference between

  • The setTimeout timers in node are executed one by one, and browsers are separated one by one
  • In the browser environment, microtasks are executed after each macro task, whereas in Node microtasks are executed between phases, with mircroTask executed immediately after each phase

conclusion

Browser environment:

while(true){macro task queue. Shift () microtask queue all tasks ()}Copy the code

Node environment:

while(trueLoop. ForEach ((phase)=>{phase all Tasks () nextTick all tasks () microTask all tasks ()})}Copy the code

60. React Fiber

React originally used the Stack Reconciler scheduling algorithm. The page may get stuck, because React will immediately start the reconciliation process after setState, iterating for differences, and rendering will not happen until all the virtual DOM has been iterated. In the process of harmonization, the main thread is occupied by JS, so interaction, layout will stop, will be stuck

So Fiber Reconciler is now used for optimization

  • Task split
  • Updates are paused, terminated, and reused
  • Setting the Priority
  • Render can return multiple elements

Scheduler

Scheduling is a process of fiber harmonization

If the UI is going to perform well, there’s a lot more to consider

  • Not all states need to be updated immediately, such as those that are not visible
  • Not all updates have the same priority, such as user input having a higher priority than the request resource display
  • High-priority updates should interrupt low-priority updates

So the process of reconciling is to do one small task at a time, and then check to see if there are any higher-priority tasks that need to be done

Fiber data structure

  • Return: the parent node
  • Child: first child node
  • Sibling: sibling node
fiber {
  	stateNode: {},
    child: {},
    return: {},
    sibling: {},
}
Copy the code

Task split

The unit of Fiber splitting is based on the virtual DOM node, because the Fiber tree is constructed based on the virtual DOM

The task to suspend

Fiber uses the browser’s apirequestIdleCallback to allow the browser to perform certain tasks when idle

functionFiber (remaining time) {if(Remaining time > time required for the task) {do the task; }else{ requestIdleCallback(fiber); }}Copy the code

Use requestAnimationFrame to render the animation

priority

{Synchronous: 1, // Synchronous Task with the highest priority Task: 2, // Task currently being scheduled Animation 3, // Animation High: 4, // High priority Low: 5, // Low priority Offscreen: 6, // Current off-screen updates, lowest priority}Copy the code

61. The webpack process

  1. Initialization: Reads and merges parameters from the configuration file, then instantiates the plug-innew Plugin()
  2. Start compiling: Initializes one with the parameters obtained in the previous stepComplierObject load plug-in, executeCompiler.runBegin to compile
  3. Determine the entry: according to the configurationentryFind all entry files
  4. Compiling modules: fromentryGo, call the configuredloader, transform the module and find the modules that the module depends on, recurse until you find all the dependent modules
  5. Complete module compilation: This step is already usedloaderAll modules have been transformed to get the transformed new content and dependencies
  6. Output resources: Assembled according to the dependencies between the entry and the modulechunkCode block, generate file output list
  7. Output success: Write the file to the system according to the output path and file name in the configuration, and complete the construction

62. Hot updates to Webpack

Mainly rely on Webpack, Express, webSocket

  • useexpressStart the local service and respond when the browser accesses it
  • Used by the server and clientwebsocketLong connection
  • webpackListen for changes to the source file
    • After each compilation, hash values are generated, JSON files for modules that have been changed, and JS files for module codes that have been changed
    • Pass after compilingsocketPush the currently compiled hash value to the client
  • The client’swebsocketListen for the hash value pushed by a file change and compare it with the last one
    • Consistency goes cache
    • If not, get the latest resources through Ajax and JSONP
  • Use an in-memory file system to replace modified content for local updates

63. CommonJs and ES6 modularity differences

  • CommonJs supports dynamic import, ES6 does not
  • CommonJs is a synchronous import, ES6 is an asynchronous import
  • CommonJs import is a copy of the value. If the export changes, it will not change, but ES6 is a reference. If the export changes, the import part will change

usage

  • Export: CommonJs ismodule.exports, ES6export / export default
  • Import: CommonJs isconst x = require('xx'), ES6import xx from 'xxx'

64. Arrow functions and normal functions

Common function

  • Normally this refers to the global object Window
  • When called as an object method, this refers to an object
  • When used as a constructor, this refers to the object of new
  • You can change this with call and apply

Arrow function

  • This always points to lexical scope
  • This cannot be changed by call, apply

65. Node reads files and converts them to buffer

const fs = require('fs')
const path = require('path')
const mimeType = require('mime-types') // File type

const filePath = path.resolve('./01.png')
const data = fs.readFileSync(filePath)
const buffer = new Buffer(data).toString('base64')
const base64 = `data:${mimeType.lookup(filePath)}; base64,${buffer}`
console.log(base64)

Copy the code

66. The sort function

  • Arrays less than 10 use insert sort
  • Arrays greater than 10 use quicksort

67. Closures and self-executing functions

closure

advantages

  • Local variables can always be stored in memory
  • You can avoid using global variables

Disadvantages:

  • Excessive memory usage may cause memory leaks

Self-executing function

  • Avoid scope naming contamination
  • Improved performance and reduced scope lookups
  • Avoid global naming conflicts
  • Save the closure state

The difference between

  • Execute immediately after a function is declared, usually only once
  • Closures are designed to give external functions access to internal variables, reducing the need for global variables

68. 0.1 + 0.2! = = 0.3

Js uses IEEE 754’s double precision standard to calculate. If it encounters a decimal that is not divisible, it will take an approximate value. If it is close enough, it will think it is that value

69. React server render

Server-side rendering is React converted into HTML via Node.js and sent back to the browser. This process is called “isomorphism” because most of the application code runs on both the server and the client

advantages

Compared to a traditional SPA one-page application,

  • Better SEO because crawler tools such as search engines can view fully rendered pages directly
  • Better user experience, server rendering is fine if the network is slow, or if the device is running slowly

disadvantages

  • Because the browser and the server are different, document, window, etc., may not get, will report an error
  • The server takes up more memory

70. Principle of front-end routing

  • Hash mode, with a hash tag, no matter how the hash value is changed, the server will only receive the URL before the hash tag, by listening, okayhashchangeEvent to switch pages based on the hash
  • In history mode, use history.pushState and history.replaceState to change the URL. Changing the URL will only update the browser history, but will not cause page updatespopstateTo change the page content while disabling the default event for the A tag.

Hash mode requires no back-end configuration and is compatible. History mode requires back-end configuration

www.cnblogs.com/jcxfighting…

71. Mobx principle

  • Low development difficulty
  • Less code
  • Good rendering performance

The working principle of

  1. Defining the state makes it observable
  2. Create derivatives in response to state changes
  3. Use action to change the state

Design principles

Mobx supports one-way data flow, where actions change state and status updates change views

  • Mobx ensures that all derivatives are in a consistent state by not caching the data and recalculating it as needed
  • Derivatives that do not participate in the reaction are simply garbage collected

Mobx runs synchronously and has two benefits

  • You don’t get old derivatives
  • It’s easier to trace the stack

The main use is an autoRun function that triggers callbacks when used properties change, and does not when unused properties change.

72. Object. Create () implementation principle

Basically, you create a new object, and then you overwrite the object’s prototype as the prototype object that was passed in (similar to inheritance)

function(constructor){
    const F = function(){}
    F.prototype = constructor
    const res = new F()
    return res
}
Copy the code

73. Event penetration

Set the CSS3 attribute pointer-events to None

74. Common HTTP status codes

  • 200: Successful. The alarm is processed and returned
  • 204: Processing succeeded, but the body information returned has no content
  • 301: A permanent redirect in which the requested resource is assigned to another URL
  • 302: Temporary redirection, hoping that this access can be obtained through a different URL
  • 303: You should use get to access another URL
  • 304: indicates that the negotiation cache is available
  • 400: The request has a syntax error
  • 401: Unlicensed, verified
  • 403: Access denied, insufficient permission
  • 404: The access resource does not exist
  • 500: Request exception, possibly front-end bug
  • 503: The server is down for maintenance and cannot process requests

75. js and CSS are blocked

Js async loading and defer loading do not block page rendering or resource loading

  • Defer will load in order, async out of order
  • Defer is running after the page has been parsed and the download is delayed immediately
  • Async is executed immediately after downloading
  • Async has a higher priority when specified

Inline and external JS

  • Embedded JS blocks loading of all resources
  • External JS blocks subsequent content rendering and resource downloading

css

  • CSS does not block DOM parsing, it blocks rendering, because rendering takes place when the DOM tree is combined with the style tree to generate a rendering tree
  • CSS blocks subsequent JS statements

If the CSS is followed by embedded JS, it blocks because the browser maintains the CSS after JS order and the stylesheet must be loaded before the embedded JS.

Load order

  • Js executes immediately in the head, blocking subsequent resource downloads and execution. Because JS may modify the DOM, the order of DOM operations is not controllable without blocking.
  • Js execution depends on CSS. Js will not be executed until all the previous CSS has been downloaded

Pay attention to

  • The CSS should be placed in the head so that the page can be rendered as quickly as possible because it does not block resource downloads
  • The js should be placed at the bottom of the body to allow the DOM to render as quickly as possible to avoid dom blocking
  • CSS blocks JS execution, it does not block JS download, but js will not execute until the CSS is loaded to play

Before executing the JS code, the browser must ensure that all CSS styles before JS are parsed, otherwise it will be messy. The previous CSS styles may overwrite the element styles defined in the JS file, which is the root cause of CSS blocking subsequent JS execution.

76. Implicit conversion

  • Numeric operator
  • The dot operator
  • In the if statement
  • = =

Blog.csdn.net/itcast_cn/a…

77. React first screen optimized

  1. Using browser caching
  2. Webpack JS compression, HTML compression
  3. Extract common resources
  4. Change the WebPack development environment to the production environment
  5. Use Sprite
  6. Use the CDN

78. Object.assign

If the object has only one layer, it is a deep copy, and if it has multiple layers, it is a shallow copy

const obj1 = {
  a: 1,
  b: {
    c: 2
  }
}

const obj2 = Object.assign({}, obj1)
console.log(obj1 == obj2)
console.log(obj1, obj2)
obj1.b = 2
console.log(obj1 == obj2)
console.log(obj1, obj2)
Copy the code

79. The innerHtml and outerHtml

  • Inner is just inside the tag, outer is including the tag

80. Rem and em

  • Rem is based on the font size of the root element
  • Em is based on the font size of its element, and if it does not have one, it can inherit the font size from its parent element

81. Garbage collection mechanisms and memory leaks

The garbage collection

  • Mark clear

The most common method of garbage collection is to mark variables at runtime, and if the variables in the environment are no longer accessible to them, they are cleared

Var m = 0,n = 19 var m = 0,n = 19 Add (m, n) // Mark a, B, and c as entering the environment. Console. log(n) // A, B, and C are marked as leaving the environment and waiting for garbage collection.function add(a, b) {
  a++
  var c = a + b
  return c
}
Copy the code

For example, local variables and parameters of a function that cannot be accessed externally are cleared

  • Reference counting

Determine the number of times a resource is referenced

var arr = [1, 2, 3, 4];
arr = [2, 4, 5]
Copy the code

For example, if the number of references to [1,2,3,4] is 1, it will not be cleared. If the number of references to [1,2,3,4] is 0, it will be cleared

A memory leak

  1. Unexpected global variables
function foo(arg) {
    bar = "this is a hidden global variable";
}
Copy the code

This way bar is declared in the global variable and will not be released

  1. If setInterval is not turned off, the timer will always exist and will not be released

  2. Closures Closures hold local variables and cannot be released

  3. A reference to a DOM element will persist if it is not cleared

To optimize the

  1. An array of optimization
Var arr = [1,2,3] arr.length = 0Copy the code
  1. Object reuse
var t = {}

while(){
    t.a = 1
}

t = null
Copy the code

Reuse objects as much as possible and do not generate them every time and then set them to NULL and garbage collect

  1. Loop through function expressions
function t(){
    
}

while(){
    t()
    // var t = function(){} this way you don't have to create many functions through a loop}Copy the code

Write Promise and promise.all by hand

Promise

Juejin. Cn/post / 684490…

The following is an abbreviated version

function myPromise(executor) {
  this.state = 'pending';
  this.value = undefined;
  this.reason = undefined;
  this.onResolvedCallbacks = [];
  this.onRejectedCallbacks = [];
  let resolve = value= > {
    if (this.state === 'pending') {
      this.state = 'fulfilled';
      this.value = value;
      this.onResolvedCallbacks.forEach(fn= >fn()); }};let reject = reason= > {
    if (this.state === 'pending') {
      this.state = 'rejected';
      this.reason = reason;
      this.onRejectedCallbacks.forEach(fn= >fn()); }};try {
    executor(resolve, reject);
  } catch (err) {
    reject(err);
  }
}

myPromise.prototype.then = function (onFulfilled, onRejected) {
  // Declare the returned promise2
  let promise2 = new Promise((resolve, reject) = > {
    if (this.state === 'fulfilled') {
      onFulfilled(this.value)
    };
    if (this.state === 'rejected') {
      onRejected(this.reason)
    };
    if (this.state === 'pending') {
      this.onResolvedCallbacks.push((a)= > {
        onFulfilled(this.value)
      })
      this.onRejectedCallbacks.push((a)= > {
        onRejected(this.reason)
      })
    }
  });
  // Return promise, complete the chain
  return promise2;
}

new myPromise((resolve, reject) = > {
  console.log('1')
  resolve(1)
  console.log('2')
}).then((res) = > {
  console.log(res)
  console.log('4')
  return 2
})
Copy the code

Promise.all

const myPromiseAll = function (promiseList){
    const result = []
    return new Promise((resolve, reject) = > {
        let index = 0
        next()
        function next(){
            promiseList[index].then((res) = > {
                result.push(res)
                index++
                if(index === promiseList.length){
                    resolve(result)
                } else {
                    next()
                }
            })
        }
    })
    
}
Copy the code

83. Post’s method

  • Application/X-www-form-urlencoded (URL upload parameters)
  • Multipart /form-data (upload file)
  • Application /json
  • text/xml

HTTP Options precheck request

Before the official cross-domain, the option request will be initiated, so as to pre-check. Check whether the sent request is safe, and send the request address, request method, the server determines whether the source domain name is in the permissibility list, request method support, support will allow the request

Precheck is sent only for complex requests, which are described below

  • Put, DELETE, patch, or POST
  • Send json format (Content-Type: application/json)
  • There are custom headers in the request

Why precheck? Complex requests can have side effects on the server, data modification, and so on. So check to see if the source of the request is on the approved list

85. Three main features of OOP

  • encapsulation
  • inheritance
  • polymorphism

86. Limit concurrency by handwriting

function limitPromise(taskList, limit) {
  return new Promise((resolve, reject) = > {
    let index = 0
    let active = 0
    let finish = 0
    let result = []

    function next() {
      if (finish >= taskList.length) {
        resolve(result)
        return
      }

      while (active < limit && index < taskList.length) {
        active++
        let cur = index
        taskList[index].then((res) = > {
          active--
          finish++
          result[cur] = res
          next()
        })
        index++
      }
    }
    next()
  })
}
Copy the code

87. Tree shaking for Webpack

Tree Shaking is a way to clean up useless code and webpack3/4 integrates automatically when it starts

88. GetComputedStyle and style

  • GetComputedStyle is read-only, and style is readable and writable
  • Style can only get inline styles

window.getComputedStyle(dom, null).getPropertyValue('display')

89. Weird Box model

  • Standard box model: size = Content + Margin + padding + border

  • Weird box model: size = width (Content + padding + border) + margin

  • Content-box: Default, standard box model

  • Border-box: Border and padding are counted in width

    .container {
      display: flex;
      width: 200px;
      height: 50px;
    }

    .item1 {
      width: 50%;
      background: red;
      border: 10px solid black;
    }

    .item2 {
      width: 50%;
      background: yellow;
    }

  <div class="container">
    <div class="item1">1</div>
    <div class="item2">2</div>
  </div>
Copy the code

The effect is shown in figure

Let’s say two divs are placed in a row, each 50% wide, and if we add a border to one of them, the other one will be squeezed

We can set box-sizing to border-box

.item1 {
  width: 50%;
  background: red;
  border: 10px solid black;
  box-sizing: border-box;
}
Copy the code

The squeeze problem is gone

90. Object.defineProperty

Object.defineproperty (obj, prop, Descriptor) MDN Description: Object on which obJ defines attributes. Prop Specifies the name of the property to define or modify. Descriptor Property descriptor to be defined or modified.Copy the code
  • Value: indicates the value
  • Writable: Indicates whether it can be rewritten
  • Enumberable: whether enumerable (for.. In the Object. The keys)
  • set/get
  • Configrable: Indicates whether it is redefinable

91. How does HTTP reuse connections

Set the HTTP header: Connection: keep-alive to tell the server that I’m going to make another request later and avoid another three-way handshake

The relationship between HTTP and TCP

  • HTTP is the application layer and TCP is the transport layer
  • HTTP is implemented on the basis of TCP
  • TCP simply connects, while HTTP sends and receives data

93. Advantages of Node

  • It’s all JS syntax
  • High concurrency is good
  • Non-blocking I/O
  • Short development cycle
  • Single process, single thread

94. HTTP packet structure

  • Request message: request line, request header, blank line, request data
  • Response message, status line, message header, blank line, response body

Request header

  • Request method: GET/POST
  • Host: requests the host
  • Connection: indicates the connection status
  • The cache-control: cache
  • Accept: indicates the type that can be sent
  • The user-agent: agent
  • Reference: Indicates the URL of the requested resource
  • Accept-encoding: indicates the supported encoding mode
  • Cookie: a cookie

Response headers

  • Date: indicates the response time
  • Last-modify: indicates the last modification time
  • Etag: indicates the resource identifier
  • Connection: indicates the connection status
  • Content-type: indicates the resource type

95. async / await

async

Async always returns promises

  • Resolve (undefined) return promise.resolve(undefined)
  • Resolve (data) return promise.resolve(data)
  • Return a promise and you get a promise

await

  • Await can only be used in async
  • If await is not a promise, get the value of resolve inside

Difference from Generator

Async is the syntactic sugar for generator

Improvements to Async over Generator

  1. Built-in actuators that do not need next to execute
  2. Better semantics
  3. Return a promise, and you can continue

96. Are there three handshakes for every request

If there is no cache, the connection:keep-alive header is set to avoid re-shaking the handshake

97. TCP keepAlive and HTTP keep-alive

  • The TCP keepAlive function keeps the connection between the client and the server. The keepAlive function periodically sends heartbeat packets to verify whether the connection is down. If this function is not used, the connection between the client and the server will be affected greatly

  • HTTP keep-alive allows the server client to keep the connection alive without the need to re-establish the TCP connection

98. TCP two handshake is ok

If a connection request for the first time, did not confirm if the server side, the client request again, and then they start connection, after that, if only delay, for the first time, and then sent to the client now, if did not shake hands three times, directly open the connection, but the client is no data to transmit, the server will have been waiting for the client to send data

99. Can data be transmitted in TCP three-way handshake

The first and second handshake is not allowed, because it is easy to be attacked. The third handshake has entered the establishment state, and the sending and receiving capability of the two parties has been confirmed, so it can be transmitted

100. 2MSL wait status

MSL is the maximum lifetime of packets. After entering the timewait state, the client needs to wait 2msl to ensure that the last ack will not be lost and the connection is normally closed. Time_wait is used to prevent the last ack may be lost

101. websocket

HTTP connections are passive and can only actively ask the server to see if there are new messages, polling all the time.

Websocket is a persistent protocol that does not automatically disconnect when connected. And you only need to send a nod of the message. A handshake, a persistent connection

  1. The TCP three-way handshake is performed first
  2. After the TCP connection is established, the browser sends the version number and address supported by the WebSocket to the server through HTTP
  3. If the protocol version matches and the packet format is correct, the server accepts the Connection (Upgrade: websocket, Connection: Upgrade).
  4. After the browser receives the reply, the onOpen event is triggered, and the data can be sent through SEND

102. hasOwnProperty

This method only iterates over its own properties, not from the stereotype chain, and can be used to determine whether the property is inherited from the object or the stereotype chain

const obj = new Object()
obj.num = 1

Object.prototype.fn = function(){
    console.log(2)
}

obj.hasOwnProperty(num) // true
obj.hasOwnProperty(fn)  // false
Copy the code

103. DNS domain name resolution

Domain name Resolution Process

  1. Check the browser cache for the IP address of the domain name
  2. Check the local cache for the IP address of the domain name
  3. Sends a domain name resolution request to the local Domain Name Resolution Service (LDNS)
  4. Sends a domain name resolution request to the root DNS server
  5. The root DNS server returns the gTLD DNS server address
  6. Initiate a resolution request to the gTLD server
  7. GTLD Server Returns Name Server Server
  8. Name Server The Server returns the IP address to the local Server
  9. The local DNS server caches the resolution result
  10. Returns the parse result to the user

Domain name Resolution mode

  • A Record: A stands foraddressIs used to specify the IP address corresponding to the domain name
  • MX record: you can point a Mail Server under a domain name to your Mail Server
  • CNAME record: alias resolution. You can resolve the specified domain name to another domain name
  • NS record: Specifies a specific DNS server to resolve a domain name
  • TXT records: specifies a description for a host name or domain name

104. JWT principle

Using a JWT server eliminates the need to store session data, making it easier to scale

The data structure

It consists of three parts, with the middle. separated

  • header
  • payload
  • signature

header

{
    "alg": "HS256"."typ": "JWT"
}
Copy the code

Alg stands for algorithm, TYP stands for type, and finally base64 encoding is converted to a string

payload

In addition to the official fields, we can also customize fields, such as:

{
    "name": "bb"."age": 21}Copy the code

signature

This is a signature that prevents previous data from being tampered with

We need to customize a key, not to be known to the user, and then generate a signature

Use mode and characteristics

use

  • The client can save the cookie or localStorage after receiving the cookie
  • Each request can be added to the custom request headerAuthorization

The characteristics of

  • Default is not encrypted, you can use the key to encrypt again
  • The session state cannot be saved and is valid until the validity period
  • Use HTTPS whenever possible to prevent leaks

105. What is a DOCTYPE and what it does

DOCTYPE is used to declare document types and DTD specifications. It is used to verify the validity of files. To improve browser compatibility, you need to set

106. Principles of koa

Koa was developed based on Express, but it is much simpler, freer, and very lightweight. Functions are implemented through plug-ins, which are in line with the Unix philosophy

Instead of using generator, KOA2 uses async/await

Differences with Express

Express:

  • More features are integrated
  • But a callback letter is inconvenient

Koa:

  • Using async/await is more convenient
  • You need to configure your own plug-in middleware, etc

structure

application.js

This is an entry file that inherits events and can perform event listening and trigger events.

  • Listen is passed a callback function that encapsulates http.createServer, including middleware, context, and RES
  • Use is a collection of middleware that puts multiple middleware into a cache queue, composed with koa-compose

context.js

This is the koA application context CTX, through which you can access the request header, set the response, etc

request/response.js

Encapsulate native REq, RES, etc. You can get headers here and set headers/body, etc

The onion model

app.use(async (ctx, next) => {
    console.log(1);
    await next();
    console.log(6);
});

app.use(async (ctx, next) => {
    console.log(2);
    await next();
    console.log(5);
});

app.use(async (ctx, next) => {
    console.log(3);
    ctx.body = "hello world";
    console.log(4);
});
Copy the code

Output 1, 2, 3, 4, 5, 6

That is to say, finish the content before await next() from top to bottom and then finish the content after await next() from bottom to top

Koa uses the use function to push the middleware to the queue, and the Onion model can make all the middleware execute in sequence, passing the CTX argument through next() after each execution

Next () acts as a baton, passing parameters and so on to the next middleware. Just execute next and the rest of the middleware will be executed!

Unlike the Express framework, modifying the response needs to wait until the request is complete, but with KOA you can put the code to modify the response after Next

Pre-processing -> deliver and wait for other middleware to handle -> post-processing

107. Babel fundamentals

What is the Babel

Babel is a JS compiler that converts code into browser-compatible code

  • The syntax conversion
  • The missing features are added by polyfill
  • Js source code conversion

Babel fundamentals

The core is the AST abstract syntax tree.

  1. Parsing: Parsing the source code into abstract syntax trees, lexing, parsing
  2. Transforming the abstract syntax tree into a new syntax tree
  3. Generating: Generating JS code for the new syntax tree

108. NPM version number

The version number

The version number is X.Y.Z

  • Big change, down incompatible, need to update X
  • Added functionality, backward compatibility, update Y
  • Fix bugs and update Z

The specific symbol

  • ~: approximate match, fixed Y, Z arbitrary change
  • ^: Compatible with a version, fixed X, Y, Z changes
  • X: Any version, for example1.x.2Can be1.4.2.1.8.2

Git rebase and merge

  • Rebase: cancels every commit of the branch, updates to the latest branch, finds the first commit of both branches, extracts all subsequent records, and adds them to the end of the target branch.
  • Merge: Merge two branches into one branch and commit two commits. Create a new commit object and make both branches’ previous records point to the new commit object, preserving all previous commits

110. The React principle of the Router

The main reliance is on the history library.

The top-level router listens for history, and when history changes, the router calls setState to pass location down. Set to RouterContext. Router Determines whether to display the router based on the RouterContext.

The Link tag disables the default event for the A tag and calls the history.push method to change the URL.

111. document.readyState

  • Loading: THE DOM is still loading
  • Interactive: The DOM is finished loading, but images, CSS, etc are still loading
  • It’s complete

112. symbol

The symbol function returns a value of type symbol, which does not support new.

  • Resolve attribute name conflicts
  • Private property

113. Samsite cookie

The cookie property SameSite has three values

  • Strict: forbid third-party cookies completely. Cookies are never sent across sites under any circumstances.
  • Lax: Disallow third-party cookies in most cases, except for GET requests that navigate to the target URL (e.g. A tag, preload request, GET form)
  • None: Turns off the Samesite property, but must be setsecureTo take effect

The difference between Async and Promise

  • More concise
  • You can use try/catch for error handling
  • Intermediate values can be easily passed to the next promise, without the need for a promise to remain then
  • Easy to track the error, error will be reported to the specific line

115. How are import and require implemented in the browser

import

You need to use Babel to convert to the commonJS specification

export

For example, export default is converted to exports.default

// Babel before compilingexportDefault {} // Babel after compiling"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = {};
/*
* exports
* {default: {} , __esModule: true} * /Copy the code

import

Use _interopRequireDefault for compatibility and differentiation between CommonJS and ES6

// import Test, {MSG, fn} from'test'// Babel is compiled'use strict';

var _test = require('test');

var _test2 = _interopRequireDefault(_test);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Copy the code

Webpack adds an __esModule: true flag for import and export to indicate that this is an ES6 thing

116. Difference between Target and currentTarget

  • Target: Returns the source object that triggered the event
  • CurrentTarget: Object that returns the event binding
  document.getElementById('test').addEventListener('click'.function (e) {
    console.log(e.target)
    console.log(e.currentTarget)
  })

  <div id="test">
    <button>1</button>
  </div>
Copy the code

117. Why is javascript single threaded

  • Preventing DOM rendering conflicts
  • Web workers in HTML5 can implement multithreading

118. DNS preresolution

  • After downloading the HTML source code, it will parse the tag of the link contained in the page and query the corresponding domain name in advance
  • A list of domain names is recorded for visited pages, and DNS is resolved when the HTML is downloaded again
Preparse a domain name <link rel="dns-prefetch" href="//img.alicdn.com"> Forcibly enable DNS preresolution in HTTPS <meta http-equiv="x-dns-prefetch-control" content="on">
Copy the code

119. What are bundle, chunk, and module

  • Bundles are files that are packaged by webpack
  • Chunk refers to the chunk of code separated by webpack’s code for module dependency analysis
  • A module is a single module in development

120. What is loader and plugin

  • Loader is webpack’s ability to load and parse non-JS files
  • Plugin can extend the functionality of Webpack to make it more flexible.

121. Lazy loading principle of components

  • For example,react-loadableThe main use ofimport()To return a promise property to loading asynchronously.
  • Webpack throughrequire.ensure()To load on demand

require.ensure

The require. Ensure (dependencies, callback, errorCallback, chunkName) he will return to a promise, first determine whether dependencies are loaded, loaded, access to the cache value. If not, make a promise and cache it. Then a script tag is generated, the information is filled into the HTML file, and the on-demand loading is complete.

Require. ensure allows custom file names

122. HTML5 offline cache

With the MANIFEST attribute, when the browser finds the manifest attribute in the header, it will request the MANIFEST file, and if it is the first time, it will download the resource based on the file content. If the offline cache has already been used, the offline resource is loaded directly.

123. How to prevent clickjacking

By nesting iframe, the attacker sets iframe as transparent and induces users to click.

This can be set via HTTP headersX-FRAME-OPTIONSTo defend against nested iframe clickjacking attacks

124. Observer versus publish and subscribe

Observer model

  function Subject() {
    this.state = 0
    this.observers = []
  }
  Subject.prototype.attach = function (observer) {
    this.observers.push(observer)
  }
  Subject.prototype.getState = function () {
    return this.state
  }
  Subject.prototype.setState = function (state) {
    this.state = state
    this.noticefyAllObservers()
  }
  Subject.prototype.noticefyAllObservers = function () {
    this.observers.forEach(observer => {
      observer.update()
    })
  }

  function Observer(name, subject) {
    this.name = name
    this.subject = subject
    this.subject.attach(this)
  }
  Observer.prototype.update = function () {
    console.log(this.name, this.subject.getState())
  }

  const subject = new Subject()
  const o1 = new Observer('o1', subject)
  const o2 = new Observer('o2', subject)
  const o3 = new Observer('o3', subject)

  subject.setState(1)
  subject.setState(2)
  subject.setState(3)
Copy the code

Publish and subscribe model

  function Event() {
    this.events = {}
  }
  Event.prototype.on = function (event, fn) {
    if(! this.events[event]) { this.events[event] = [] } this.events[event].push(fn) } Event.prototype.emit =function (event) {
    const args = [...arguments].splice(1)
    this.events[event].forEach(fn => {
      fn.apply(this, args)
    })
  }
  Event.prototype.off = function(event, fn) { const currentEvent = this.events[event] this.events[event] = currentEvent.filter(item => item ! == fn) } const publisher = new Event() const fn1 =function (e) {
    console.log('a1')
    console.log(e)
  }
  const fn2 = function (e) {
    console.log('a2')
    console.log(e)
  }
  publisher.on('a', fn1)
  publisher.on('a', fn2)
  publisher.emit('a'.'aowu')
  publisher.off('a', fn2)
  publisher.emit('a'.'aowu')
Copy the code

The difference between

  • In the observer mode, the observer knows the subject. In the publish and subscribe mode, the publisher and the subscriber do not know the existence of each other and only communicate through the message broker
  • The observer pattern is mostly synchronous and the publish-subscribe pattern is mostly asynchronous
  • Most publish-subscribe patterns are loosely coupled, and observers vice versa

128. Nginx load balancing

www.cnblogs.com/alterem/p/1… www.jianshu.com/p/4c250c1cd…

129. redis

www.imweb.io/topic/58441…

130. Set,Map,WeakSet,WeakMap

  • Set: traversable, unique element
  • WeakSet: All elements are objects, and all elements are weak references, which can be garbage collected. It is not easy to cause memory leakage and cannot be traversed
  • Map: key-value pairs that can be traversed
  • WeakMap: Key name object, key name is weak reference, cannot be traversed

131. Difference between token and cookie

token

  • The encryption and decryption takes a long time and occupies a large memory
  • Support not only browser, but also mobile etc
  • Can prevent CRSF attacks
  • Tokens are stateless and easily extensible

cookie

  • Automatic sending, convenient
  • The APP side cannot use cookies
  • Not using HTTPS is vulnerable to CRSF attacks

132. Null and undefined

  • Null: The object type, which is the end of the prototype chain of the object, is defined and null
  • Undefined: indicates that no value is assigned. Undefined is of the type

React uses persist

React synthetic event calls are reused after they are called, and all properties are invalid. For asynchronous access, use event.persist(), which will be removed from the event pool, allowing references to the event to remain

134. Position: relative affects attributes such as the child element offsetLeft

135. What is the difference between applets and H5

  1. The rendering mode of applet is different from that of H5. Generally, applet is rendered through Native, but applet also supports Web rendering. You can initialize a WebView component to load H5 pages in the Webview

In small programs, native mode performs better than Web mode

  1. Applets unique dual – threaded design. Under H5, we usually pack it all in one file. After compiling the small program, there are two, respectively, view layer, and business logic. At runtime, there are two threads processing two files, one is the main render thread, which is responsible for rendering the contents of the View layer. The other is the Service worker thread, which executes the business logic.
  • Running environment is different, H5 mostly used in web-view or browser, small program is using a built-in parser based on browser reconstruction, greatly optimized performance, cache and so on
  • Performance is different, small programs rely on wechat client implementation, a lot of optimization of the analysis, the first open will cache a lot of resources, so much smoother than H5, low-level optimization technology makes small programs more close to the original APP
  • Small program development cost is low, do not need to worry about puzzling bugs, you can call the official API
  • Wechat has more users and more traffic than H5
  • Applets cannot use DOM
  • Applets can use many phone permissions

136. Strings slice, substr, substring

  • Slice: Normal slice, reverse if there is a negative number
  • Substr: The first argument is the start subscript and the second argument is how many characters to cut
  • Substring: Pass in two arguments, the smaller of which is the starting index

137. Basic types of packaging

Primitive types are not objects, but they have methods. Why?

This is because the background wraps primitive types, such as strings, integers, and booleans, which are first created using constructors and then destroyed

let s1 = 'hello'
letS2 = s1.substring(2) // ↓ Background packinglet s1 = new String('hello') / / packagingletS2 = s1.substring(2) // call s1 = null // destroyCopy the code

138. With the valueOf toString

  • Null and undefined do not have these methods
  • ToString: The value type returns the string form and the Object type returns the ibject Object form
  • ValueOf: Both the value and reference type are returned unchanged. If the value is Date, the timestamp is returned
  • ToString is preferred for string conversions and valueOf is preferred for numeric computations
  • ToString supports passing parameters and conversion to base

139. Es6’s class implements private variables

  1. closure
class A {
    constructor (x) {
        let _x = x
        this.showX = function () {
            return _x
        }
    }
}

letA = new a (1) // cannot access a._x // undefined // can access A.shox () // 1Copy the code
  1. Using the symbol
Class A {constructor(x) {constructor(x) {const _x = symbol ('x'// Use symbol to declare the private variable this[_x] = x}showX() {
    return this[_x]
  }
}

letA = new a (1) // 1. A [_x] Uncaught ReferenceError: _x is not defined // 2. Const x = Symbol() const x = Symbol()'x') a[x] // undefined; The third way is to access (correct) a.shox () //1Copy the code

140. TypeScript Types and Interfaces

interface

  • The same nameinterfaceAutomatic aggregation can also be with the same nameclassAutomatic aggregation
  • Can only sayobject.function.classtype

type

  • Not just to indicateobject.function.classtype
  • Can’t wish
  • Supports complex type operations

141. V8 engine for JavaScript

JavaScript engine

JavaScript is an interpreted language, and unlike compiled languages, JS is parsed as it is executed. Java virtual machines and C++ compilers have been introduced to improve performance

Execute the process

Source code -> Abstract syntax tree -> bytecode -> JIT -> native code

V8 engine

Compared to other javascript engines (converted to bytecode or interpreted execution), V8 compiles code directly to native machine code, using inline caching to improve performance.

Workflow: The source code is parsed into an abstract syntax tree and then the JIT compiler generates code directly from the abstract syntax tree, making code execution faster (without converting to bytes)

142. Difference between heap and stack

  • Heap: Mainly stores new and other allocated memory blocks, the compiler does not automatically free them, reference type in the heap
  • Stack: mainly storing function parameters, local variables, etc., the compiler automatically allocates and releases, basic data types in the stack

143. unicode utf8 utf16

  • Unicode is designed to solve the problem of encoding inconsistency in the world. It contains all the symbols and characters in the encoding set. Each character is represented by two bytes. English characters only need one byte, so it wastes space to save
  • Utf8 is a variable length encoding with 8 bits at a time. It uses 1 to 4 bytes to represent a symbol. Utf8 Chinese characters usually use 3 bytes
  • Utf16 transmits 16 bits at a time

The difference between

Utf8, UTF16: are unicode character sets, different encoding implementations

144. What is the difference between class and function

  • Class packaging is more reasonable, easy to maintain and use
  • Class does not rise in state like function does
  • Class doesn’t have to write the prototype method which is a little bit easier
  • Class requires super to use this