Writing in the front

In the front end, JS is the soul, is the basis of all logic, is the fundamental technology of the front end engineers, learn JS in the framework of learning and learning the bottom no longer talk about, the text details part of the basic knowledge of JS.

To eat: Primary front-end taste index: 😋😋😋😋😋

1. What are the data types of JS? ⭐ ⭐ ⭐ ⭐ ⭐

Values of reference types are stored in the heap, variables stored in the stack and memory addresses that point to values in the heap. This is stored because of performance issues. Basic data types:

  • Number
  • String
  • Boolean
  • Null
  • Undefined
  • Symbol (ES6 new data type)
  • bigInt

Reference data types:

  • Object
  • Array
  • Date
  • Function(special, but not used to store data, so there is no “copy” Function)
  • RegExp

2. How to determine the data type in JS? ⭐ ⭐ ⭐ ⭐

Typeof: 1. Can judge all value types (string, number, Boolean, undefined, Symbol) 2. 3. Can identify reference types (can’t continue to identify)

Instanceof: 1. Determine whether the object pair is on the prototype chain of the target object 2. It is generally used to distinguish reference types, not the basic data type of literals

Object. The prototype. ToString. Call () can distinguish between specific basic types and reference types

console.log(Object.prototype.toString.call("kerwin")); // "[object String]" 
var arr = [1.2.3];
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
Copy the code

3. The handwritten instanceof ⭐ ⭐ ⭐

// Iterate through the prototype chain of A, return true if b.prototype is found, false otherwise

const _instanceof = (A, B) = > {
  let p = A
  while(p) {
    if(p === B.prototype) {
      return true
    }
    p = p.__proto__
  }
  return false
}
Copy the code

4. Var and let const ⭐⭐⭐⭐⭐

  • Var is an ES5 syntax, and let const is an ES6 syntax. Var is promoted, but let and const are also promoted, with a temporary dead zone that is unavailable until defined
  • Var and let are variables that can be modified. Const is a constant that cannot be modified. However, we can modify the value of an object declared using const
  • Let const has block-level scope; var does not

5. What are the differences between array traversal schemes? ⭐ ⭐ ⭐ ⭐

For: The most basic common kind of loop, needless to say

  1. The continue statement is used to break out of this loop, but continues to execute subsequent loops.
  2. The break statement is used to terminate the loop, and subsequent loops are not executed.
  3. A return cannot be used to break out of a for loop. A return statement can only appear inside a function, terminating the function and returning a specified value.

ForEach: executes a supplied function once on each element of the array, taking three arguments: the contents of the current loop item, the index of the current loop, and the array of the loop

Map () : the method loops through each item in turn and returns the result map to form a new array. Using forEach, map cannot break the loop. The method completes each item before ending the loop.

For in: iterates over a key (the key that traverses an object, array, or string). This is best used to iterate over an object.

  1. Index The index is a string number (note that it is not a number) and cannot be directly used for geometric operations.
  2. The traversal order may not be in the internal order of the actual array (possibly in random order).
  3. Using for-in iterates through all enumerable properties of a set, including stereotypes. Typically, you need to use the hasOwnProperty() method to determine whether an attribute is an instance attribute of the object to remove the prototype object from the loop.

For-of: iterates over values (iterates over values of objects, arrays, or strings)

  1. This is the simplest and most straightforward syntax for iterating through a list of elements, avoiding all the pitfalls of a for-in loop.
  2. Unlike forEach(), it responds correctly to break, continue, and return statements.
  3. Therefore, the recommendation is to use for-of to iterate over the array, because for-of only iterates through the elements of the array, not including the array’s prototype property Method and index name.

6. What is a prototype chain? ⭐ ⭐ ⭐ ⭐ ⭐

Archetypal relationship:

  1. Each constructor shows the prototype prototype
  2. Each instance has an implicit stereotype _proto_
  3. The _proto_ of the instance points to the prototype of the corresponding constructor
  4. To obtain a property or method, search for it from its own property or method first. If it cannot find it, search for it in _proto_ automatically

The prototype chain: When accessing a property of an object, it looks for the property itself. If not, it looks for its __proro__ implicit prototype, which is its constructor’s prototype. If not, it looks for its constructor’s __proto__. Object. Prototype. — proto — ===null

7. What are free variables ⭐⭐⭐⭐

Free variable: A variable is not defined in the current scope, but is used. If the global scope is not found, then an error is reported. All free variables are searched in the function definition, in the upper scope, not in the execution place

8. What is scope, scope chain ⭐⭐⭐⭐ port

Scope:

  • A scope determines the visibility of variables and other resources in a block of code. A scope is an independent domain that keeps variables from leaking out
  • In other words, the greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict.
  • Before ES6, JavaScript had no block-level scope, only global scope and function scope. With the advent of ES6, we have block-level scopes

Scope chain:

  • When a desired variable cannot be found in its scope, it looks up one level at a time,
  • The search is abandoned until the global scope is not found. This layer by layer relationship is the scope chain

Scope and execution context: The execution of JavaScript is divided into two stages: interpretation and execution.

  • Lexical analysis
  • Syntax analysis
  • Scope rules are determined

Execution stage:

  • Create execution context
  • Execute function code
  • The garbage collection
  1. The JavaScript interpretation phase determines the scope rule, so the scope is defined when the function is defined, not when the function is called, but the execution context is created before the function executes.
  2. The most obvious execution context is that the reference to this is determined at execution time, while the scoped variables are determined by the structure of the code being written.

The biggest differences between scope and execution context are:

  • The execution context is determined at run time and can change at any time; The scope is defined at definition and does not change.
  • Different calls to the same scope have different execution contexts, so this refers to different things

9. Say this⭐⭐⭐⭐⭐

  1. This is defined at function execution time, not at definition time. This refers to window by default and is undefined in strict mode
  2. Implicit binding: that is, this refers to the nearest caller, which is the object immediately preceding the function. Call, apply, bind (); call, apply, bind (); call, apply, bind ();
  3. The this in the constructor refers to the instance object created by the function
  4. The arrow function itself does not have this, which is inherited from its parent scope. This cannot be modified by bind, call, or apply.
  5. This in the immediate-execute function is simply a word: always refer to the global window

10. Talk about closures ⭐⭐⭐⭐ service

A closure is a function that can read variables inside other functions.

  1. Whichever way an inner function is passed outside its lexical scope, it holds a reference to the original scope, and the function uses closures wherever it is executed.
  2. The value of these variables is kept in memory at all times because the execution of the closure depends on the variables in the external function, and the memory occupied by the variables is not freed until the closure is complete

Application:

  1. Closures are typically used to define modules, where we expose the operation functions to the outside and hide the details inside the module
  2. If the throttle

11. A handwritten apply ⭐ ⭐ ⭐

Function.prototype.myApply = function(context) {
  const ctx = context || window
  // The most important step is 1. This inside myApply refers to the caller fn function.
  // ctx.func is the fn function. CTX calls the fn function, so this inside the fn function refers to CTX
  ctx.func = this
  let result = arguments[1]? ctx.func([...arguments[1]]) : ctx.func()
  delete ctx.func
  return result
}
Copy the code

12. Write a bind ⭐ ⭐ ⭐

Function.prototype.bind1 = function () {
  // Split the parameters into arrays
  const args = Array.prototype.slice.call(arguments);
  // Get this(first item of array)
  const t = args.shift();
  //fn1.bind(...) The fn1
  const self = this
  // Return a function
  return function () {
    return self.apply(t, args)
  }
}
Copy the code

13. Handwriting flatern, consider multilevel ⭐⭐⭐

function flat(arr) {
  const isDeep = arr.some(item= > item instanceof Array)
  if(! isDeep) {return arr  // Already flatern
  }
  constres = [].concat(... arr)// Each element in arR is concatenated
  return flat(res)
}
Copy the code

14. Write a new ⭐ ⭐ ⭐

function myNew(fn, ... args) {
  // Create an empty object
  let obj = {}
  // Make the implicit prototype of the empty object point to the explicit prototype of the original function
  obj.__proto__ = fn.prototype
  // this points to obj
  let result = fn.apply(obj, args)
  / / return
  return result instanceof Object ? result : obj
}
Copy the code

15. Handwriting trim ⭐⭐⭐

String.prototype.trim = function () {
  return this.replace(/^\s+/.' ').replace(/\s+$/.' ')}Copy the code

16. Handwritten Currification ⭐⭐⭐

Implementations such as add(1)(2)(3)(4)= 10Add (1)(1,2,3)(2)=9 refer to changing a function that takes multiple arguments to a fixed form that takes one argument and returns one function

function add() {
  let args = Array.from(arguments)
  let adder = function() { args.push(... arguments)return adder
  }
  adder.toString = function() {
    return args.reduce(function(a, b){
      return a + b
    }, 0)}return adder
}
let a = add(1.2.3)
let b = add(1) (2) (3)
console.log(a)
console.log(b)
console.log(a==6)
console.log(b==6)
ƒ () {args.push(... ƒ () {args.push(... arguments) return adder } true true */
Copy the code

17. Handwritten depth comparison ⭐⭐⭐⭐

// Check whether it is an object or an array
function isObject(obj) {
  return typeof obj === 'object'&& obj ! = ='null'
}

function isEqual(obj1, obj2) {
  if(! isObject(obj1) || ! isObject(obj2)) {// Value type (note that participants in equal are generally not functions)
    return obj1 === obj2
  }
  // Both are objects or arrays and are not equal
  //1. First fetch obj1 and obj2 keys and compare the number
  const obj1Keys = Object.keys(obj1)
  const obj2Keys = Object.keys(obj2)
  if(obj1Keys.length ! == obj2Keys.length) {return false
  }
  //2. Compare with obj2 recursively against obj1
  for (let key in obj1) {
    if(! isEqual(obj1[key], obj2[key])) {return false}}return true
}
Copy the code

18. Handwritten deep copy ⭐⭐⭐⭐⭐

function deepClone(obj = {}) {
  if(typeofobj ! = ='object' || obj == null) {
    //obj is null, or is not an object or array
    return obj;
  }
  // Initialize the result
  let result;
  if (obj instanceof Array) {
    result = [];
  } else {
    result = {};
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // recursive callresult[key] = deepClone(obj[key]); }}return result;
}
Copy the code

19. What is DOM? ⭐ ⭐ ⭐

DOM:

  • The DOCUMENT Object Model (DOM) defines standards for accessing HTML and XML documents.
  • DOM maps the entire page as a multi-tier node structure, and each component of an HTML or XML page is a node of some type, which in turn contains different types of data.
  • It allows programs and scripts to dynamically access and update the content, structure, and style of documents.
  • DOM node has 12 types, such as element node, text node and attribute node. There are many methods to obtain nodes and operate nodes

20. Introduce Ajax and write ⭐⭐⭐⭐⭐

Ajax principle:

  • The browser’s javascript object XMLHttpRequest(Ajax engine) object sends an asynchronous request to the server and receives the server’s response data, then updates the page by manipulating the DOM with javascript. One of the most critical steps is getting the request data from the server.
  • The user’s request is made indirectly through the Ajax engine rather than directly through the browser, and the Ajax engine also receives data from the server in response, so it doesn’t cause a full page refresh on the browser.
// Write it by hand, usually as a promise wrapper
function ajaxPromiseGet() {
  const p = new Promise((resolve, reject) = > {
    const xhr = new XMLHttpRequest()
    xhr.open('GET'.'test.json'.true)
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText))
        } else if (xhr.status === 404) {
          reject(new Error('404 not found'))
        }
      }
    }
    xhr.send(null)})return p
}
Copy the code

xhr.readyState:

  • 0-(uninitialized) The send() method has not been called
  • 1-(load) The send() method has been called and the request is being sent
  • 2-(load complete) The send() method is complete and all corresponding contents have been received
  • 3-(Interaction) Parsing the response content
  • 4-(done) The corresponding content is parsed and can be called on the client

xhr.status:

  • 2xx- Indicates that the request was successfully processed, such as 200
  • 3xx- Redirection required. To switch to the browser, go to 301, 302, and 304
  • 4xx- Client request error, such as 404 403
  • 5xx- Server error

21. What is JSON? ⭐ ⭐ ⭐

  • Json is a data format that is essentially a string
  • Json structure and JS object structure is consistent, more friendly to JS language
  • Window. JSON is a global object: json. stringify, json.parse
  • You can’t have single quotes, you need double quotes

22. Introduce JS garbage collection mechanism ⭐⭐⭐⭐

The garbage collection mechanism collects objects:

  • Values of primitive types in JavaScript are stored in stack memory and are automatically allocated and freed by the system.
  • The value of the reference type is stored in heap memory and its lifetime is determined by the JavaScript engine’s garbage collection mechanism.

Garbage collection mechanisms are divided into reference counting and marker clearing reference counting:

  1. The basic idea is to keep track of how many times each value is referenced. When a value has zero references, it is safe to reclaim its memory because no variable references it.
  2. The garbage collector will free the memory of the value referenced 0 on the next garbage collection.

To quote the problem of counting:

  • Circular reference. That is, object A has A property pointing to B, and object B has A property pointing to A.
  • Both A and B will have A reference count of 2 and will never be collected by the garbage collector. Over time, a large amount of memory cannot be reclaimed, resulting in memory leaks. Because there are more obvious problems, so mainly exist in the early IE browser

Reachable: Reachable values are values that are accessible or available in some way that will not be cleared or released by the garbage collection mechanism. Reachable values are important criteria for determining whether a value will be garbage collected. The following is a set of inherently reachable values that occupy space that cannot be freed.

  • Local variables and arguments to the current function
  • Nested calls call the variables and arguments of all functions in the chain
  • Global variables and some internal ones

These values are called roots, and a value is considered reachable if it can be accessed from the root through a reference or chain of references. The garbage collector periodically performs the following steps for garbage collection.

  1. The garbage collector finds all the roots and marks them
  2. Traverse and mark the reference to the root
  3. The references to the references are then marked until all reachable objects are marked
  4. Any remaining objects that are not marked are deleted

Today’s major browsers use tag clearing to manage memory for reference values

24. What is cross-domain ⭐⭐⭐⭐⭐

Important: Cross-domain does not mean that the request cannot be sent out. The request can be sent out, and the server can receive the request and return the result normally, but the result is blocked by the browser. Why intercept?

  • Same-origin policy: When making An Ajax request, the browser requires that the current web page and the server must be of the same origin. The cornerstone of browser security is the same-origin policy
  • Cognate: The protocol, domain name, and port must be the same
  • Objective: To ensure the security of user information and prevent malicious websites from stealing data.

Exception:

  1. Loading images, CSS, js can ignore the same origin policy
  2. <img/>Can be used for statistics, can use third party statistics services
  3. <link/>``<script>CDN can be used, and CDN is generally an outfield

25. What about JSONP cross-domain? ⭐ ⭐ ⭐ ⭐ ⭐

The json principle: The link in the SRC attribute of the script tag can access cross-domain JS scripts. With this feature, the user passes a callback parameter to the server, which then returns the JSON data as a function name wrapped around the callback parameter. The server does not return JSON data. Instead, it returns a piece of JS code that calls a function, called in SRC, which implements cross-domain JSONP advantages and disadvantages

  • JSONP has the advantage of simple compatibility and can be used to solve the problem of cross-domain data access in mainstream browsers.
  • The disadvantage is that only support for get methods is limited and insecure and may be subject to XSS attacks.

26. Introduce CORS cross-domain? ⭐ ⭐ ⭐ ⭐ ⭐

CORS Cross-domain: CORS is the fundamental solution to cross-source AJAX requests. JSONP can only make GET requests, but CORS allows any type of request. As soon as the browser discovers that an AJAX request crosses sources, it automatically adds some additional headers, and sometimes an additional request, but the user doesn’t notice. Therefore, the key to CORS communication is the server. As long as the server implements the CORS interface, cross-source communication is possible. Browsers classify CORS requests into two types: simple request and non-simple request Simple request: the following two conditions should be met: (1) The request method is one of the following three methods:

  • HEAD
  • GET
  • POST

(2) HTTP Request Headers does not exceed any of the following fields:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-type: Application/X-www-form-urlencoded, multipart/form-data, text/plain
  1. For simple requests, the browser issues CORS requests directly. Specifically, add an Origin field to the header information
  2. The origin field indicates the source (protocol + domain name + port) from which the request is sent. Based on this value, the server decides whether to approve the request or not
  3. If Origin specifies a domain name within the license, the server returns a response with several additional header fields
  4. Most importantly access-Control-Allow-Origin this field is required. Its value is either the value of the Origin field at the time of the request, or an *, indicating acceptance of requests for any domain name.
  5. There are also fields that control whether cookies are sent, etc

Non-simple request:

  1. Non-simple requests are requests that have special requirements on the server, such as the request method being PUT or DELETE, or the content-Type field being of Type Application/JSON.
  2. For CORS requests that are not simple requests, an HTTP query request is added before formal communication, which is called a precheck request
  3. The request method for the “precheck” request is OPTIONS, indicating that the request is being queried. In the header information, the key field is Origin, indicating which source the request came from.
  4. In addition to the Origin field, the precheck request header contains two special fields.
  • Access-Control-Request-Method

This field is required to list which HTTP methods are used by the browser for CORS requests, in this example PUT.

  • Access-Control-Request-Headers

This field is a comma-separated string that specifies the additional Header field to be sent by a browser CORS request, x-custom-header in the example above.

  • After receiving a pre-check Request, the server checks the Origin, access-Control-request-method, and access-Control-request-headers fields to confirm that cross-source requests are allowed. The key to the response is also the Access-Control-Allow-Origin field

PS:

  • For HTTP request methods that may have adverse effects on server data (especially HTTP requests other than GET, or POST requests with certain MIME types), the browser must first initiate a preflight request using the OPTIONS method. To know whether the server allows the cross-domain request.
  • The actual HTTP request is made only after the server confirms that it is allowed. In the return of the precheck request, the server side can also inform the client whether it needs to carry identity credentials (including Cookies and HTTP authentication related data).

27. What about Nginx? ⭐ ⭐ ⭐ ⭐ ⭐

  1. Forward proxy: It is generally used for personal access to the inside of a service. For example, if you want to access Google, but in normal circumstances, you cannot access it. In this case, we will spend money or find a proxy server for free to let it access Google, and then return data to you through it. He does not know who is actually accessing it. This process is a forward proxy.
  2. Reverse proxy: For example, in order to ensure Intranet security, prevent Web attacks, achieve load balancing and reduce request pressure, a proxy server, such as Nginx, is set up before the Web node. At this time, users access the Nginx proxy server. For users, He does not know which real server node is serving him. This process is a reverse proxy.

For example: the current front-end domain name is http://127.0.0.1. The back-end server domain name is: If you need to start an nginx server, do the following configuration in the configuration file nginx.conf

server {
    listen  80;
    server_name 127.0.0.1;

    location / {
        proxy_pass  http://127.0.0.1:3000;
    }

    location ~ /api/ {
        proxy_passhttp://github.com; }}Copy the code

The above configuration can be interpreted as:

Listen on port 80 (Nginx starts port 80 by default) and forward all requests from http://127.0.0.1 to port 127.0.0.1 for 3000; The request is forwarded to http://github.com http://127.0.0.1/api/ or http://127.0.0.1/api/xxxxx

There is no cross-domain between servers and servers, and Nginx takes advantage of this by having the front end access to the same-origin server, which forwards requests to servers in different domains to fetch data

Write in the last

Thank you very much for reading to the end, if you think it is helpful to you, I hope you can click on the “like”, if you have any questions, please feel free to contact me, I hope we can progress together. Finally, I wish you a bright future, we climb each other, high meet 🌈!